views:

94

answers:

1

I have an existing bit of code for sorting a list of objects.

productsList.Sort(
    delegate(Product p1, Product p2)
    {
        int result =  p1.StartDatetime.CompareTo(p2.StartDatetime);
        if (result == 0)
        {
           if (p1.SomeId == p2.SomeId)
           {
               result = 0;
           }
           else if (p1.SomeId == null)
           {
                result = -1;
           }
           else if (p2.SomeId == null)
           {
                result = 1;
           }
        }
        return result;
    });

I have a feeling that this can be simplified by replacing it with:

productsList = productsList
         .OrderBy(p => p.StartDatetime)
         .ThenBy(p => p.SomeId)
         .ToList();

Am I correct in my assumption?

+1  A: 

Not quite but it's close. The first could order

List<Product> productsList = new List<Product>() {
    new Product { StartDatetime = new DateTime(2010, 1, 1), SomeId = 2 },
    new Product { StartDatetime = new DateTime(2010, 1, 1), SomeId = 4 }
};

in the opposite order (with SomeId equals 4 first and SomeId equals 2 second) but the second will order them as the Product with SomeId equals 2 first and the Product with SomeId equals 4 second. This is because the delegate, as it is currently defined, does not handle any case where two SomeIds are non-null and different. So, as far as the delegate concerned, the above two Products are "equal" but according to the LINQ query they are not.

Jason