Let's go

对List排序处理

案例一、

    class Program
    {
        static void Main(string[] args)
        {
            List<Student> stuList = new List<Student>();

            Student obj1 = new Student();
            obj1.id = 1;
            Student obj2= new Student();
            obj2.id =2;
            Student obj3 = new Student();
            obj3.id =3;
            Student obj4 = new Student();
            obj4.id = 4;
            stuList.Add(obj1);
            stuList.Add(obj2);
            stuList.Add(obj3);
            stuList.Add(obj4);
            stuList.Add(obj2);
            //排序输出结果
            Console.WriteLine("正常输出==》");
            foreach (var item in stuList)
            {
                Console.WriteLine(item.id);
            }

            stuList.Sort(new T_Asc());  //传递接口实现类来实现排序(升序)

            //排序输出结果
            Console.WriteLine("升序输出==》");
            foreach (var item in stuList)
            {
                Console.WriteLine(item.id);
            }

            stuList.Sort(new T_Desc());  //传递接口实现类来实现排序(降序)

            //排序输出结果
            Console.WriteLine("降序输出==》");
            foreach (var item in stuList)
            {
                Console.WriteLine(item.id);
            }
            Console.ReadLine();
        }
        public class T_Asc : IComparer<Student>
        {
            public int Compare(Student x, Student y)
            {
                return x.id.CompareTo(y.id);
            }
        }
        public class T_Desc : IComparer<Student>
        {
            public int Compare(Student x, Student y)
            {
                return y.id.CompareTo(x.id);
            }
        }
        public class Student
        {
            public int id { get; set; }
        }
    }

 

posted @ 2021-07-08 19:45  chenze  阅读(64)  评论(0编辑  收藏  举报
有事您Q我