string[] strs = { "1", "111", "11", "999", "77" }; List<string> list = strs.ToList(); list.Sort(delegate (string s1, string s2) { return int.Parse(s1).CompareTo(int.Parse(s2)); });
下面介绍各种List的sort的用法与比较
首先,我们建一个People的实体,有name、age、sex的属性,我们要排序的字段是年龄age
新建一个实体类
public class People { public string name { get; set; } public int age { get; set; } public string sex { get; set; } }
新建list的数据
List<People> peoples = new List<People>() { new People() {age = 11, name="alun", sex = "男"}, new People() {age=25, name = "陈敬桃", sex = "男"}, new People() {age=9, name = "惠安", sex = "男"}, new People() {age = 45, name = "小票", sex = "女"}, new People() {age=3, name = "晓鸥", sex = "女"}, new People() {age=70, name = "望谟", sex = "男"} };
1. 第1种排序方法,使用 IComparer
public class PeopleAgeComparer : IComparer<People> { public int Compare(People p1, People p2) { return p1.age.CompareTo(p2.age); } } peoples.Sort(new PeopleAgeComparer());
可以看到第一种方法比价麻烦,要新建一个新的类来做
2. 第2种排序方法,使用委托来排序
peoples.Sort(delegate (People p1, People p2) { return p1.age.CompareTo(p2.age); });
看委托的方式很方便,不用新建类这么麻烦。
3. 第2种排序方法,使用Lambda表达式来排序
peoples.Sort( (a, b) => a.age.CompareTo(b.age) );