对集合排序,可能最先想到的是使用OrderBy方法。
class PRogram{static void Main(string[] args){IEnumerable<Student> result = GetStudents().OrderBy(r => r.Score);foreach (var item in result){Console.WriteLine(item.Name + "--" + item.Score);}Console.ReadKey();}private static List<Student> GetStudents(){return new List<Student>(){new Student(){Id = 1, Name = "张三",Age = 15, Score = 80},new Student(){Id = 2, Name = "李四",Age = 16, Score = 70},new Student(){Id = 3, Name = "赵武",Age = 14, Score = 90}};}}public class Student{public int Id { get; set; }public string Name { get; set; }public int Age { get; set; }public int Score { get; set; }}
以上,OrderBy返回的类型是IEnumerable<Student>。
如果想使用List<T>的Sort方法,就需要让Student实现IComparable<Student>接口。
class Program{static void Main(string[] args){List<Student> result = GetStudents();result.Sort();foreach (var item in result){Console.WriteLine(item.Name + "--" + item.Score);}Console.ReadKey();}private static List<Student> GetStudents()
新闻热点
疑难解答