tags:

views:

614

answers:

2

I have a List that I need to sort by datatime, the class MyStuff looks like:

public class MyStuff
{
   public int Type {get;set;}
   public int Key {get;set;}
   public DateTime Created {get;set;}
}

I need to be able to sort the collection List by the Created (datetime) field.

+1  A: 
var query = 
    from m in mystuffcollection
    orderby m.Created ascending
    select m;
popester
+5  A: 

You seem to be working with a List<T> object, in which case the most efficient (and a simple) method would be the following:

myList.Sort((x, y) => DateTime.Compare(x.Created, y.Created));

This uses the overload of the List.Sort method than takes a Comparison<T> delegate (and thus lambda expression).

You can of course use the LINQ OrderBy extension method, but I don't think this offers any advantages, and can be significantly slower, depending on your situation.

myList = myList.OrderBy(x => x.Created).ToList();
Noldorin
I would not worry about "performance" here. Although props for pointing out no LINQ/sort-by needed.
pst
The key difference between the two methods is that `List<T>.Sort` sorts the existing list, while `OrderBy` returns a new `IEnumerable<T>` and leaves the list alone. That's either an advantage if you want to keep the original list, or a performance hit if you don't.
stevemegson
@stevemegson: This is very true. However, in-place sorts are typically more common.
Noldorin
Also very true. Of course under the hood they're both really in-place sorts, you just get to choose which place. OrderBy more or less calls Array.Sort(myList.ToArray()), while myList.Sort calls Array.Sort directly on the List's internal array. More or less.
stevemegson
Noldorin