C#对List排序的三种方式的比较
对List排序,有三种方式,自定义比较器、lamda排序、自定义方法排序。以下是源码:
1 using System; 2 using System.Collections.Generic; 3 4 namespace CustomDLL 5 { 6 public class PeopleCompare : IComparer<People> 7 { 8 public int Compare(People x, People y) 9 { 10 return x.age.CompareTo(y.age); 11 } 12 } 13 14 public class People 15 { 16 public int age; 17 } 18 19 public class City 20 { 21 List<People> allPeople = new List<People>(); 22 23 PeopleCompare peopleCompare = new PeopleCompare(); 24 //自定义比较器排序 25 public void SortPeopleFun1() 26 { 27 allPeople.Sort(peopleCompare); 28 } 29 30 //Lamda排序 31 public void SortPeopleFun2() 32 { 33 allPeople.Sort((a, b) => { return a.age.CompareTo(b.age); }); 34 } 35 36 //自定义方法排序 37 public void SortPeopleFun3() 38 { 39 allPeople.Sort(Sort); 40 } 41 42 int Sort(People a, People b) 43 { 44 return a.age.CompareTo(b.age); 45 } 46 } 47 }
生成dll,通过反编译查看下这三种方式的区别:
观察源码行数和反编译的结果,可以发现,自定义方法对List排序应该被优先选择的。