你可以使用List.Sort()
。但是,如果您想使用此方法,存储在列表中的对象的类型应该实现IComparable
界面。下面我为您提供了一个代码示例,您可以基于该示例编写自己的代码:
public class Customer : IComparable<Customer>
{
public int Age { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Customer(int age, string firstName, string lastName)
{
Age = age;
FirstName = firstName;
LastName = lastName;
}
public int CompareTo(Customer other)
{
return Age.CompareTo(other.Age);
}
}
class Program
{
static void Main(string[] args)
{
List<Customer> customers = new List<Customer>
{
new Customer(25,"a","b"),
new Customer(21,"c","d"),
new Customer(22,"e","f"),
new Customer(28,"g","i"),
new Customer(30,"j","k"),
new Customer(23,"l","m"),
new Customer(31,"a","b"),
};
customers.Sort();
foreach (var customer in customers)
{
Console.WriteLine(customer.Age);
}
Console.ReadKey();
}
}
关于复杂性List.Sort()
方法,如其中所述MSDN,
平均而言,此方法是一个 O(n log n) 操作,其中 n 是 Count;
在最坏的情况下,它是一个 O(n ^ 2) 操作。