C#中的IComparer接口

C#中的IComparer接口

1前言
本文通过一个简单的例子,说明如何通过传递实现IComparer接口的类,对ArrayList集合中的元素按照自定义的排序逻辑进行排序。
2例子
2.1定义StudentInfo类

    public class StudentInfo
    {
        public string id;//学号
        public string name;//姓名
        public string address;//家庭住址
        public StudentInfo(string id, string name, string address)
        {
            this.id = id;
            this.name = name;
            this.address = address;
        }
        public void Show()
        {
            Console.WriteLine(id + ", " + name + ", " + address);
        }
    }

2.2定义实现IComparer接口类,该类对学生按照姓名进行降序排序

    public class StudentNameCompare : IComparer
    {
        public int Compare(object x, object y)
        {
            return new CaseInsensitiveComparer().Compare(((StudentInfo)y).name,((StudentInfo)x).name);
        }
    }

2.3利用实现IComparer接口的类对学生信息进行排序

            ArrayList arrayList = new ArrayList();
            StudentInfo customer1 = new StudentInfo("Id002","王三","河南郑州市");
            arrayList.Add(customer1);
            StudentInfo customer2 = new StudentInfo("Id001","赵大","山东菏泽市");
            arrayList.Add(customer2);
            StudentInfo customer3 = new StudentInfo("Id003","钱二","湖北武汉市");
            arrayList.Add(customer3);
            Console.WriteLine("排序前的集合排列");
            for (int i = 0; i < arrayList.Count; ++i)
            {
                StudentInfo customerInfoElement = (StudentInfo)arrayList[i];
                customerInfoElement.Show();
            }
            Console.WriteLine("排序后的集合排列");
            arrayList.Sort(new StudentNameCompare());
            for (int i = 0; i < arrayList.Count; ++i)
            {
                StudentInfo customerInfoElement = (StudentInfo)arrayList[i];
                customerInfoElement.Show();
            }

2.4执行结果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值