What you’re ordering by here is the distance between the pivot (the birthdate) and each date. Something like this:
var sorted = data.OrderBy(date => (birthdate - date).TotalDays);
will sort by distance, but put all the after dates first, because the TotalDays will be negative, then the before dates. To avoid that, we need to implement a custom IComparer which compares absolute values, and falls back to the real values in case of equality:
public class AbsoluteComparer : IComparer<double>
{
public int Compare(double x, double y)
{
var absX = Math.Abs(x);
var absY = Math.Abs(y);
if (absX > absY)
return 1;
if (absX < absY)
return -1;
// If Absolutes are equal, determine by sign.
if (x > y)
return 1;
if (y > x)
return -1;
return 0;
}
}
So the final call would be:
var sorted = data.OrderBy(date => (birthdate - date).TotalDays, new AbsoluteComparer());
3
solved Sort date using lambda expression [closed]