C# 类添加排序接口和排序规则

比较和排序的概念:

    比较:两个实体类之间按>,=,<进行比较。

    排序:在集合类中,对集合类中的实体进行排序。排序基于的算法基于实体类提供的比较函数。

    基本型别都提供了默认的比较算法,如string提供了按字母进行比较,int提供了按整数大小进行比较。

当我们创建了自己的实体类,如Student,默认想要对其按照年龄进行排序,则需要为实体类实现IComparable接口:

    /// <summary>
    /// 类排序需继承IComparable接口
    /// </summary>
    class Student : IComparable<Student>
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }

        #region IComparable<Student> Members 默认接口实现

        public int CompareTo(Student other)
        {
            return Age.CompareTo(other.Age);
        }
        #endregion
    }

    //名字升序排列
    class SortNameASC : IComparer<Student>
    {
        #region IComparer<Student> Members

        public int Compare(Student x, Student y)
        {
            return x.Name.CompareTo(y.Name);
        }

        #endregion
    }

    //名字降序排列
    class SortNameDSC : IComparer<Student>
    {
        #region IComparer<Student> Members

        public int Compare(Student x, Student y)
        {
            return y.Name.CompareTo(x.Name);
        }

        #endregion
    }

    //年龄升序排序
    class AgeASC : IComparer<Student>
    {
        public int Compare(Student x, Student y)
        {
            return x.Age.CompareTo(y.Age);
        }
    }
    //年龄降序排序
    class AgeDESC : IComparer<Student>
    {
        public int Compare(Student x, Student y)
        {
            return y.Age.CompareTo(x.Age);
        }
    }

    /// <summary>
    /// 实现
    /// </summary>
    public MainWindow()
    {
        InitializeComponent();
        List<Student> stulist = new List<Student>
        {
            new Student(){Age=24,Id=1001,Name="小明"},
            new Student(){Age=23,Id=1003,Name="小花"},
            new Student(){Age=21,Id=1004,Name="小强"},
            new Student(){Age=22,Id=1002,Name="小海"}     
        };
        //stulist.Sort();//默认排序
        stulist.Sort(new SortNameDSC());
        foreach (Student item in stulist)
        {
            Console.WriteLine(item.Age + "\t" + item.Id + "\t" + item.Name + "\r\n");
        }
    }

猜你喜欢

转载自blog.csdn.net/lvxingzhe3/article/details/121886901