列表排序

在使用List<>的时候,有可能需要对List中内容进行排序,可以使用List的内置排序机制Sort方法进行排序,但是List中的数据类型需要实现IComparable借口。
在下面的例子中 Square就实现了IComparable借口,根据面积进行排序:

class Program
    {
        static void Main(string[] args)
        {
            var data = new List<Square>() { new Square(5, 10), new Square(2, 3), new Square(1, 8), new Square(4,6) };
            foreach (var d in data)
                Console.WriteLine(d.ToString());

            data.Sort();

            foreach (var d in data)
                Console.WriteLine(d.ToString());

            Console.ReadKey();
        }
    }

    public class Square : IComparable<Square>
    {
        public Square(int height, int width)
        {
            Height = height;
            Width = width;
        }

        public int Height { get; set; }
        public int Width { get; set; }

        public int CompareTo(object obj)
        {
            Square square = obj as Square;
            if (square != null)
                CompareTo(square);
            throw
                new ArgumentException("Both objects being compared be of type Square");
        }

        public override string ToString() => ($"Height:{this.Height} Width:{this.Width}");
        public int CompareTo(Square other)
        {
            long area1 = this.Height * this.Width;
            long area2 = other.Height * other.Width;

            if (area1 == area2)
                return 0;
            if (area1 > area2)
                return 1;
            return -1;
        }
    }

输出结果:
这里写图片描述

如果字典类型想要排序,可以使用SortedDictionary<TKey, TValue>类型,在使用add方法是会进行排序
例:

 var dic = new SortedDictionary<int, Square>() { { 0, new Square(5, 10) }, { 1, new Square(2, 3) }, { 2, new Square(1, 8) }, { 3, new Square(4, 6) } };

输出结果:
这里写图片描述

如果别人定义一个数据类型,却未提供排序方法,而你有无法修改这个数类型时,可以使用IComparer 接口。下面例子定义了CompareHeight,实现IComparer接口,对Square对象的高度进行排序。
例:

ublic class CompareHeight : IComparer<Square>
    {
        public int Compare(Square x, Square y)
        {
            if (x.Height == y.Height)
                return 0;
            if (x.Height > y.Height)
                return 1;
            return -1;
        }
    }

p

使用代码:

var data1 = new List<Square>() { new Square(5, 10), new Square(2, 3), new Square(1, 8), new Square(4, 6) };
data.Sort(new CompareHeight());

结果:
这里写图片描述

另外还可以使用lambda表达式实现:

  data.Sort((x, y) =>
            {
                if (x.Height == y.Height)
                    return 0;
                if (x.Height > y.Height)
                    return 1;
                return -1;
            });

结果也是一样的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

刘建宁

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值