zoukankan      html  css  js  c++  java
  • C#学习笔记(14)——C# 使用IComparer自定义List类的排序方案

    说明(2017-7-17 21:34:59):

    原文:https://my.oschina.net/Tsybius2014/blog/298702?p=1

    另一篇比较好的:https://wenku.baidu.com/view/b53cd250ad02de80d4d84073.html

    摘要: C# 使用IComparer自定义List类的排序方案

    List类中不带参数的Sort函数可以用来为List类中的元素排序,但如果List类中的元素类型本身不能直接进行比较(如自定义的struct和很多class),或是希望采用更加灵活的自定义比较方式,可以通过继承了IComparer接口的函数来解决。

    代码示例如下:

    1)声明一个类

    /// <summary>
    /// 人物类
    /// </summary>
    public class Person
    {
        public string Name;
        public int Age;
        public override string ToString()
        {
            return "Name: " + Name + " Age: " + Age;
        }
    }

    2)声明一个继承了接口IComparer的类

    /// <summary>
    /// 比较人物类实例大小,实现接口IComparer
    /// </summary>
    public class PersonComparer : IComparer<Person>
    {
        public int Compare(Person x, Person y)
        {
            if (x == null && y == null) return 0;
            if (x == null) return -1;
            if (y == null) return 1;
    
            //TODO:Person类实例X与Y的比较规则
            //按姓名由小到大排列,姓名相同的人年龄大的在前
            {
                int temp = string.Compare(x.Name, y.Name);
                if (temp > 0) return -1;
                else if (temp < 0) return 1;
    
                if (x.Age > y.Age) return 1;
                if (x.Age < y.Age) return -1;
            }
    
            return 0;
        }
    }

    3)Main函数,建立一个List,并使用刚建立的PersonComparer类中的规则对List进行排序

    static void Main(string[] args)
    {
        List<Person> a = new List<Person>();
    
        a.Add(new Person() { Name = "Tsybius", Age = 23 });
        a.Add(new Person() { Name = "Galatea", Age = 21 });
        a.Add(new Person() { Name = "Lucius", Age = 22 });
        a.Add(new Person() { Name = "Septimus", Age = 22 });
        a.Add(new Person() { Name = "Octavius", Age = 22 });
        a.Add(new Person() { Name = "Lucius", Age = 24 });
    
        //输出a中全部元素
        Console.WriteLine("排序前");
        foreach (var v in a)
        {
            Console.WriteLine(v.ToString());
        }
        Console.WriteLine("-");
    
        //对a进行排序
        a.Sort(new PersonComparer());
    
        //输出a中全部元素
        Console.WriteLine("排序后");
        foreach (var v in a)
        {
            Console.WriteLine(v.ToString());
        }
        Console.WriteLine("-");
    
        Console.ReadLine();
    }

    4)程序运行示例

    END

  • 相关阅读:
    Linux 下安装配置 JDK7
    win7下virtualbox装linux共享win7文件问题(已测试可用)
    Linix常用命令
    JAVA命令大全
    virtualbox 不能为虚拟电脑打开一个新任务/VT-x features locked or unavailable in MSR.
    VirtualBox下安装rhel5.5 linux系统
    redhat RHEL 5.5 下载地址
    ios开发@selector的函数如何传参数/如何传递多个参数
    U盘10分钟安装linux系统
    史上最浅显易懂的Git分布式版本控制系统教程
  • 原文地址:https://www.cnblogs.com/Jacklovely/p/7197655.html
Copyright © 2011-2022 走看看