简体   繁体   English

C#中的列表排序

[英]list sorting in c#

我有对象列表,我需要根据对象的property1对列表进行排序,并且我需要再次对具有对象的property2的结果列表进行排序,而不会丢失在第一次排序中完成的分组..例如:obj具有2个属性名称和位置i需要具有已按区域排序的对象的最终列表,而相同区域的对象应按名称排序...

(Assuming you don't have LINQ available to you, which makes this trivial.) (假设您没有可用的LINQ,这很简单。)

If you look in MiscUtil , you'll find two useful classes: ProjectionComparer and LinkedComparer (IIRC). 如果您查看MiscUtil ,则会发现两个有用的类: ProjectionComparerLinkedComparer (IIRC)。

ProjectionComparer basically implements the LINQ "order by" concept - you specify how to convert a source element to a key value, and the comparer will order by those key values. ProjectionComparer基本上实现了LINQ“按顺序排序”的概念-您指定如何将源元素转换为键值,比较器将按这些键值进行排序。

LinkedComparer takes two comparers and returns a new comparer which uses the "primary" comparer first, and the "secondary" comparer if values are equal with respect to the primary one. LinkedComparer两个比较器,并返回一个新的比较器,该比较器首先使用“主要”比较器,如果值与主要比较器相等,则使用“第二”比较器。

Create two projection comparers (one for each property) and then a linked comparer with the two of them, then pass that to List<T>.Sort . 创建两个投影比较器(每个属性一个),然后创建一个具有两个投影比较器的链接比较器,然后将其传递给List<T>.Sort Let me know if you need a full code sample, but it would be something like (using C# 3): 让我知道您是否需要完整的代码示例,但是就像(使用C#3)那样:

var comparer = new LinkedComparer<Foo>
     (ProjectionComparer<Foo>.Create(x => x.FirstProperty),
      ProjectionComparer<Foo>.Create(x => x.SecondProperty));

(In C# 2 you could use anonymous methods, they'd just be a bit more long-winded.) (在C#2中,您可以使用匿名方法,它们只会有点冗长。)

听起来您想使用LINQ的orderbythenby语法。

A List has a Sort method which takes a Comparision delegate as an argument. 列表具有Sort方法,该方法将Comparision委托作为参数。 There are also overloads where you can pass in your own comparer. 还有一些重载,您可以在其中传递自己的比较器。

So, you can write a class which implements IComparer. 因此,您可以编写一个实现IComparer的类。 Then, in the implementation of this class, you write the code where you compare the 2 objects on the properties you want. 然后,在该类的实现中,编写代码,比较所需属性上的2个对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM