tags:

views:

582

answers:

7

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?

A: 

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.

Shane MacLaughlin
+4  A: 
using System.Linq;

void List<ApprovalEventDto> sort(List<ApprovalEventDto> list)
 { return list.OrderBy(x => x.EventDate).ToList();
 }
Mark Cidade
That doesn't actually do what's been specified - it doesn't sort the list, it returns an ordered view on the list. It may well be good enough, of course - but we don't really know. If the OP wants the list to be sorted in place, List.Sort is the way to go.
Jon Skeet
It still sorts the list, just not in-place.
Mark Cidade
I guess it's all a matter of what you understand by the word "sort". OrderBy doesn't modify the data source at all, whereas when someone says they want a collection to be sorted I take it to mean they want the actual collection reordered. As I said before though, it's unclear what the OP needs.
Jon Skeet
A: 

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

PiRX
+9  A: 

You can use List.Sort() as follows:

ApprovalEvents.Sort((lhs, rhs) => (lhs.EventDate.CompareTo(rhs.EventDate)));
Darksider
ApprovalEvents.Sort((lhs, rhs) => lhs.EventDate.CompareTo(rhs.EventDate)); works better...
Lette
this worked ApprovalEvents.Sort((lhs, rhs) => (lhs.EventDate.CompareTo(rhs.EventDate)));
Paul Rowland
someone with editing rights needs to fix the above answer...
TheSoftwareJedi
+3  A: 
ApprovalEvents.Sort((x, y) => { return x.EventDate.CompareTo(y.EventDate); });
Afree
Please format the code correctly.
Spoike
Note that you don't need the "new Comparison" part - type inference will work it out for you. (See DarkSider's answer.)
Jon Skeet
+1  A: 

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

Jon Skeet
A: 

Like Darksiders solution, but I prefer to keep it non-cryptic:

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