按多个字段对列表(C#)进行排序?
我想按多个字段(而不仅仅是一个字段)对 C# 中的对象列表进行排序。例如,假设我有一个名为 X 的类,它有两个属性 A 和 B,并且按顺序有以下对象:
object1 => A =“a”,B =“h”
对象2 => A =“a”,B =“c”
对象3 => A =“b”,B =“x”
对象4 => A =“b”,B =“b”
,我想首先按 A 属性对列表进行排序,当它们相等时,按 B 元素排序,因此顺序为:
“a”“c”
“一个”“h”
“b”“b”
"b" "x"
据我所知,OrderBy 方法按一个参数进行排序。
问题:如何按多个字段对 C# 列表进行排序?
I want to order a List of objects in C# by many fields, not just by one. For example, let's suppose I have a class called X with two Attributes, A and B, and I have the following objects, in that order:
object1 => A = "a", B = "h"
object2 => A = "a", B = "c"
object3 => A = "b", B = "x"
object4 => A = "b", B = "b"
and I want to order the list by A attribute first, and when they are equals, by B element, so the order would be:
"a" "c"
"a" "h"
"b" "b"
"b" "x"
As far as I know, the OrderBy method order by one parameter.
Question: How can I order a C# List by more than one field?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用
ThenBy
:请参阅 MSDN:http://msdn。 microsoft.com/en-us/library/bb549422.aspx
Use
ThenBy
:See MSDN: http://msdn.microsoft.com/en-us/library/bb549422.aspx
是的,您可以通过指定比较方法来做到这一点。优点是排序的对象不必是 IComparable
Yes, you can do it by specifying the comparison method. The advantage is the sorted object don't have to be IComparable
让您的对象类似于
还请注意 CompareTo 的返回:
http: //msdn.microsoft.com/en-us/library/system.icomparable.compareto.aspx
然后,如果您有 MyObject 列表,请调用 .Sort() 即
Make your object something like
also note that the returns for CompareTo :
http://msdn.microsoft.com/en-us/library/system.icomparable.compareto.aspx
Then, if you have a List of MyObject, call .Sort() ie
您的对象应实现 IComparable 接口。
有了它,您的类就变成了一个名为
CompareTo(T other)
的新函数。在此函数中,您可以在当前对象和另一个对象之间进行任何比较,并返回一个整数值,了解第一个对象是否大于、小于或等于第二个对象。Your object should implement the IComparable interface.
With it your class becomes a new function called
CompareTo(T other)
. Within this function you can make any comparison between the current and the other object and return an integer value about if the first is greater, smaller or equal to the second one.