zoukankan      html  css  js  c++  java
  • 搬运IComparer

    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

    悟已往之不谏,知来者之可追
  • 相关阅读:
    无限维
    黎曼流形
    why we need virtual key word
    TOJ 4119 Split Equally
    TOJ 4003 Next Permutation
    TOJ 4002 Palindrome Generator
    TOJ 2749 Absent Substrings
    TOJ 2641 Gene
    TOJ 2861 Octal Fractions
    TOJ 4394 Rebuild Road
  • 原文地址:https://www.cnblogs.com/ljh-study/p/13681941.html
Copyright © 2011-2022 走看看