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?
Not quite but it’s close. The first could order
in the opposite order (with
SomeIdequals4first andSomeIdequals2second) but the second will order them as theProductwithSomeIdequals2first and theProductwithSomeIdequals4second. This is because the delegate, as it is currently defined, does not handle any case where twoSomeIds are non-null and different. So, as far as the delegate concerned, the above twoProducts are “equal” but according to the LINQ query they are not.