方法一、sort()
(1)當list中存的是簡單數據類型時;
List<int> a = new List<int>() { 4, 5, 1, 2, 10, 78, 12, 5 }; a.Sort();//默認升序 foreach (var t in a) { Console.WriteLine(t); } Console.ReadKey();
(2)當list中存的是自定義數據類型時;
public void Sort(Comparison<T> comparison);
其中參數Comparison<T>委托的定義為:
public delegate int Comparison<in T>(T x, T y);
/// <summary> /// 定義一個數據類型 /// </summary> public class Student { public int ID { set; get; } public string Name { set; get; } public static List<Student> GetStudents() { List<Student> stu = new List<Student>(); List<int> a = new List<int>() { 4, 5, 1, 2, 10, 78, 12, 5 }; foreach (int t in a) { stu.Add(new Student { ID = t,Name="編號為"+ t +"的學生"}); } return stu; } }
//排序,sort方法參數lambda表達式,根據學生ID排序 List<Student> stus = Student.GetStudents(); stus.Sort((item1, item2) => { if (item1.ID > item2.ID) { return 1;//升序,-1降序 } else if (item1.ID < item2.ID) { return -1; } else { return 0; } }); stus.ForEach(item => Console.WriteLine(item.ID + System.Environment.NewLine + item.Name)); Console.ReadKey();
方法二、OrderBy()
public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector);
List<Student> stus = Student.GetStudents();
//升序,降序OrderByDescending stus = stus.OrderBy(item => { return item.ID; }).ToList(); stus.ForEach(item => Console.WriteLine(item.ID + System.Environment.NewLine + item.Name)); Console.ReadKey();
結果: