views:

209

answers:

1

I have a list that contains dates that are in GMT format.

What is the most elegant way to ensure that the following Lambda expression orders on the date field as GMT?

ProductsList.OrderBy(Product => Product.Added).ToList(); 
+2  A: 

The inbuilt LINQ operators use the expected sort operations (for LINQ-to-Objects, it does this using Comparer<T>.Default. Your lambda expression is strongly typed; behind the scenes the compiler inferred some generics for you - it is actually:

var newList = Enumerable.OrderBy<Product,DateTime>(
         ProductsList, Product => Product.Added).ToList(); 

It already knows it is a DateTime, so the only time you'd need to do something extra here is if your dates contain a range of different timezones. Of course, within a timezone you should be fine, but you could (if you were paranoid) convert all to UTC - I don't think you need to do this in your case, but:

var newList = ProductsList.OrderBy(
        Product => Product.Added.ToUniversalTime()).ToList();

Note that this actually creates a second list (it doesn't change the ordering of the original list); you can use the code from here to do an in-place sort using lambdas:

ProductsList.Sort(Product => Product.Added);
Marc Gravell
Thanks, just what I need!
Nicholas Murray