首页 > 代码库 > List<T>的排序

List<T>的排序

方法一、sort()

(1)当list中存的是简单数据类型时;

      public void Sort();

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();

结果:

技术分享

 

List<T>的排序