调用List<T>类中 public void Sort(Comparison<T> comparison);
例子:对集合中的User对象进行排序
public class User
{
public string Name { get; set; }
public int Age { get; set; }
public new string ToString()
{
return $"Name:{Name} , Age:{Age}";
}
}
static void Main(string[] args)
{
List<User> list = new List<User>();
list.Add(new User() { Name = "Allen", Age = 18 });
list.Add(new User() { Name = "Erlon", Age = 50 });
list.Add(new User(){Name = "Airlie", Age = 26 });
list.Add(new User(){Name = "Zalberg", Age = 40 });
list.Add(new User() { Name = "Allen1", Age = 18 });
list.Add(new User() { Name = "Allen", Age = 19 });
Console.WriteLine(string.Join("\r\n",list.Select(x=>x.ToString())));
//排序
list.Sort(((x, y) =>
{
int nameLength = x.Name.Length > y.Name.Length ? y.Name.Length : x.Name.Length;
for (int i = 0; i < nameLength; i++)
{
if (x.Name[i] == y.Name[i])
{
continue;
}
//比较姓名中的字母,小在前
if (x.Name[i] < y.Name[i])
{
return -1;
}
return 1;
}
//姓名前几位相同则比较长度,短的在前
if (x.Name.Length < y.Name.Length)
{
return -1;
}
if (x.Name.Length > y.Name.Length)
{
return 1;
}
//比较年龄,小在前
if (x.Age < y.Age)
{
return -1;
}
if(x.Age == y.Age)
{
return 0;
}
return 1;
}));
Console.WriteLine("---------------");
Console.WriteLine(string.Join("\r\n", list.Select(x => x.ToString())));
Console.ReadKey();
}