简体   繁体   English

如何对通用列表进行排序?

[英]How do I sort a generic list?

I have a generic list... 我有一个通用列表......

public List<ApprovalEventDto> ApprovalEvents public List <ApprovalEventDto> ApprovalEvents

The ApprovalEventDto has ApprovalEventDto有

public class ApprovalEventDto  
{
    public string Event { get; set; }
    public DateTime EventDate { get; set; }
}

How do I sort the list by the event date? 如何按活动日期对列表进行排序?

您可以使用List.Sort(),如下所示:

ApprovalEvents.Sort((lhs, rhs) => (lhs.EventDate.CompareTo(rhs.EventDate)));
using System.Linq;

void List<ApprovalEventDto> sort(List<ApprovalEventDto> list)
 { return list.OrderBy(x => x.EventDate).ToList();
 }
ApprovalEvents.Sort((x, y) => { return x.EventDate.CompareTo(y.EventDate); });

If you don't need an in-place sort, and you're using .NET 3.5, I'd use OrderBy as suggested by marxidad. 如果您不需要就地排序,并且您使用的是.NET 3.5,我会按照marxidad的建议使用OrderBy。 If you need the existing list to be sorted, use List.Sort. 如果需要对现有列表进行排序,请使用List.Sort。

List.Sort can take either a Comparison delegate or an IComparer - either will work, it's just a case of working out which will be simpler. List.Sort可以使用比较委托或IComparer - 要么可以工作,只需要解决一个更简单的问题。

In my MiscUtil project I have a ProjectionComparer which allows you to specify the sort key (just as you do for OrderBy) rather than having to take two parameters and call CompareTo yourself. 在我的MiscUtil项目中,我有一个ProjectionComparer,它允许您指定排序键(就像您对OrderBy一样),而不是必须采用两个参数并自己调用CompareTo。 I personally find that easier to read, but it's up to you, of course. 我个人认为更容易阅读,但当然,这取决于你。 (There are also simple ways of reversing and combining comparisons in MiscUtil. See the unit tests for examples.) (在MiscUtil中还有简单的方法可以反转和组合比较。有关示例,请参阅单元测试。)

像Darksiders解决方案,但我更喜欢保持它不神秘:

ApprovalEvents.Sort((a, b) => (a.EventDate.CompareTo(b.EventDate)));

Merge sorts work very well for lists. 合并排序可以很好地用于列表。 See WikiPedia entry for more details, basically it's a recursive n-Log n sort that doesn't require random access. 有关更多详细信息,请参阅WikiPedia条目 ,基本上它是一种递归的n-Log n排序,不需要随机访问。

For certain data types you can also use pigeon holing to get order n at the expense of more memory usage. 对于某些数据类型,您还可以使用pigeon holing来获取订单n,但代价是更多的内存使用量。

You can use List.Sort() method with anonymous method or lambda expression. 您可以将List.Sort()方法与匿名方法或lambda表达式一起使用。 More at MSDN 更多在MSDN

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

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