C# - How to implement multiple comparers for an IComparablelt;Tgt; class?(C# - 如何为 IComparablelt;Tgt; 实现多个比较器班级?)
问题描述
我有一个实现 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<T> 实现多个比较器班级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C# - 如何为 IComparable<T> 实现多个比较器班级?
基础教程推荐
- C# 从 List<List<int>> 中删除重 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
