DotNet / 编程技术 · 2022年9月14日

C#通过实现IComparable和IComparer接口进行排序

对列表的排序,之前有过介绍主要的实现方法
如果仅仅使用sort来实现排序,则只要实现IComparable<T>接口,就可以了。如果数据类排序要求复杂多变,需要进行多种的排序方式,那么,可以通过额外实现IComparer<T>来实现这种需求

IComparable<T>接口示例:
    class Human : IComparable<Human>
    {
        public int Age { get; set; }
        public int Weight { get; set; }
        public int CompareTo(Human other)
        {
            if (this.Age > other.Age)
            {
                return 1;//当前Human排在前面
            }
            else if (this.Age < other.Age)
            {
                return -1;//当前Human排在后面
            }
            else
            {
                return 0;//相同
            }
        }
    }
IComparer<T>接口示例:
    class HumanComparerByWeight : IComparer<Human>
    {
        public int Compare(Human x, Human y)
        {
            if (x.Weight > y.Weight)
            {
                return 1;
            }
            else if (x.Weight < y.Weight)
            {
                return -1;
            }
            else
            {
                return 0;
            }
        }
    }
测试代码示例:
 class Program
    {
        static void Main(string[] args)
        {
            List<Human> humanList = new List<Human>
            {
                new Human("jack",33,67),
                new Human("joke",20,61),
                new Human("bob",12,78),
                new Human("tony",78,57),
                new Human("xiaoming",23,53),
                new Human("jieni",90,53),
                new Human("lily",22,50),
                new Human("peter",36,53)
            };
            Console.WriteLine("---------Sort by Age(default)---------------");
            humanList.Sort();
            foreach (var item in humanList)
            {
                Console.WriteLine(item.ToString());
            }
            Console.WriteLine("---------Sort by Weight---------------------");
            humanList.Sort(new HumanComparerByWeight());
            foreach (var item in humanList)
            {
                Console.WriteLine(item.ToString());
            }
            Console.WriteLine("---------Sort by Name-----------------------");
            humanList.Sort(new HumanComparerByName());
            foreach (var item in humanList)
            {
                Console.WriteLine(item.ToString());
            }
        }
运行结果:
测试结果

最新电影,电视剧,尽在午夜剧场

电影电视剧午夜不寂寞