简体   繁体   中英

How do I sort a generic list?

I have a generic list...

public List<ApprovalEventDto> ApprovalEvents

The ApprovalEventDto has

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. If you need the existing list to be sorted, use 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.

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. 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.)

像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.

For certain data types you can also use pigeon holing to get order n at the expense of more memory usage.

You can use List.Sort() method with anonymous method or lambda expression. More at MSDN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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