Monday, November 17, 2008

Sorting in C# with delegates

A delegate can be handy to avoid having to implement an IComparer class.

Suppose you need to sort an array of dates in descending order...

DateTime[] availableDates = allMailDates.ToArray();
Array.Sort(availableDates, delegate(DateTime d1, DateTime d2) {
return Math.Sign(d2.ToBinary() - d1.ToBinary());


rgrig said...

I don't see any guarantee on the ordering of DateTime.ToBinary in the docs(). I don't see any guarantee on the range used (apart from 64bits, which is not enough to prevent overflow).

Yuri Chebotarev said...

ะก# 3.0 way:
Array.Sort(availableDates, (x1,x2)=>Math.Sign(x2.ToBinary() - x1.ToBinary()));