C# - 如何为 IComparable实现多个比较器班级?
我有一个实现 IComparable 的类。
public class MyClass : IComparable<MyClass>
{
public int CompareTo(MyClass c)
{
return this.whatever.CompareTo(c.whatever);
}
etc..
}
然后,我可以调用我的类的通用列表的排序方法
List<MyClass> c = new List<MyClass>();
//Add stuff, etc.
c.Sort();
,并根据我的比较器对列表进行排序。
如何指定进一步的比较器以根据 MyClass 的其他属性以不同的方式对我的集合进行排序,以便让用户以多种不同的方式对我的集合进行排序?
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.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
要在您的班级中设置排序:
然后使用新的比较进行排序:
除非您显然不想对空列表进行排序:)
To setup the sort in your class:
Then to sort using your new comparison:
Except you clearly will not want to sort an empty list :)
您可以使用特定比较器作为参数来调用 Sort。参考:MSDN
You can call Sort with a specific comparer as the argument. Reference: MSDN
朝这个方向迈出的一步是使用 Sort 重载,让您指定一个
IComparer
(但不是IComparable
)。如果您已经有很多
IComparable
实现,那么编写一个用于比较两个IComparable
实例。事实上,我有点惊讶 BCL 中不存在这样的类,但我还没有找到。IComparer
的通用实现应该是微不足道的;T>Comparer.Default
很接近,但又不完全一样。One step in that direction would be to use the Sort overload that let's you specify an
IComparer<T>
(not anIComparable<T>
, though).If you already have a lot of
IComparable<T>
implementations, it should be trivial to write a general-purpose implementation ofIComparer<T>
that compares twoIComparable<T>
instances. In fact, I'm a bit surprised such a class doesn't already exist in the BCL, but I haven't been able to find one.Comparer<T>.Default
comes close, but not quite.如果您有多种方法对对象列表进行排序,那么显然您必须指定选择哪个选项。这就是 Sort 的其他重写的好处。看看 IComparer 和 Comparison。
If you have multiple ways to sort a list of your objects, you obviously have to specify which option to choose. That's what the other overrides of Sort are good for. Have a look at IComparer and Comparison.