栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

C#中的IComparer接口

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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执行结果

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/886090.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号