C# - 如何为 IComparable<T> 实现多个比较器班级? [英] C# - How to implement multiple comparers for an IComparable<T> class?

查看:17
本文介绍了C# - 如何为 IComparable<T> 实现多个比较器班级?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实现 IComparable 的类.

I have a class that implements IComparable.

public class MyClass : IComparable<MyClass>
{
    public int CompareTo(MyClass c)
    {
        return this.whatever.CompareTo(c.whatever);
    }

    etc..
}

然后我可以调用我的类的通用列表的排序方法

I then can call the sort method of a generic list of my class

List<MyClass> c = new List<MyClass>();
//Add stuff, etc.

c.Sort();

并根据我的比较器对列表进行排序.

and have the list sorted according to my comparer.

我如何指定更多的比较器来根据 MyClass 的其他属性对我的集合进行不同的排序,以便让用户以多种不同的方式对我的集合进行排序?

How do i specify further comparers to sort my collection different ways according to the other properties of MyClass in order to let users sort my collection in a number of different ways?

推荐答案

在你的类中设置排序:

public static Comparison<MyClass> OtherComparison = delegate(MyClass object1, MyClass object2)
{
    return object1.Whatever.CompareTo(object2.Whatever);
};

然后使用您的新比较进行排序:

Then to sort using your new comparison:

List<MyClass> myClassList = new List<MyClass>();
myClassList.Sort(MyClass.OtherComparison);

除非您显然不想对空列表进行排序:)

Except you clearly will not want to sort an empty list :)

这篇关于C# - 如何为 IComparable&lt;T&gt; 实现多个比较器班级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆