对集合排序的三种方式

王朝学院·作者佚名  2016-05-20
窄屏简体版  字體: 小  |  中  |  大  |  超大  

对集合排序的三种方式

对集合排序,可能最先想到的是使用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()

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航