列表>>自己的比较器
我有一个列表,其中元素是:
struct element {
double priority;
int value;
}
如何实现自己的比较器,允许我按优先级对列表进行排序?我尝试使用 SortredList...但它不允许重复的键:(
非常感谢您的帮助!
I have a List where element is:
struct element {
double priority;
int value;
}
How can I implement my own comparer which allow me sort List by priority ? I try with SortredList... but it don't allow douplicated keys :(
Big thanks for help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
假设 C# 3 或更高版本:
Assuming C# 3 or later:
您可以使用
Sort
执行就地排序需要比较
的重载 delegate:对于旧版本的 C#,您需要将 lambda 替换为老式的 delegate 语法:
You can perform an in-place sort by using the
Sort
overload that takes aComparison<T>
delegate:For older versions of C# you'll need to swap out the lambda for old-school delegate syntax:
如果您不能依赖 C# 3 扩展或 Lambda,那么您可以让您的结构实现 IComparable 界面,如下所示:
还有一个 此接口的类型安全版本,但原理是相同的
在结构或类上实现该接口后,调用 Sort
List
方法将“正常工作”If you can't rely on C# 3 extensions or Lambdas then you can have your struct implement the IComparable interface, like so:
There are also a typesafe version of this interface, but the principle is the same
After you have that interface implemented on your struct or class, calling the Sort method on
List<>
will "just work"这取决于您是否想要对列表本身进行排序,或者按排序顺序检索值(而不更改列表)。
对列表本身进行排序(假设您有一个名为
elements
的List
):.NET 2.0 等效项:
要按排序顺序获取值:
中没有 LINQ 等效项.NET 2.0,但您可以编写自己的:
用法:
This depends on if you want to sort the list itself, or retrieve the values in sorted order (without changing the list).
To sort the list itself (supposing you have a
List<element>
calledelements
):.NET 2.0 equivalent:
To get the values in sorted order:
There's no LINQ equivalent in .NET 2.0, but you can write your own:
Usage:
如果你想对列表本身进行排序而不创建新实例,你可以实现
IComparer,然后使用您的实现实例调用 List.Sort
If you want to sort the list itself without creating a new instance, you can implement
IComparer, then call List.Sort with an instance of your implementation