C# - 如何实现一个IComparable的&LT多个comparers; T>类? [英] C# - How to implement multiple comparers for an IComparable<T> class?

查看:181
本文介绍了C# - 如何实现一个IComparable的&LT多个comparers; 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.

我如何指定进一步comparers根据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多个comparers; T&GT;类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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