Over the Christmas holidays, I thought I’d experiment with something I’d been thinking about a little – sorting a generic
IList<T>. Now, before anyone gets huffy, I’m well aware of
OrderBy in LINQ to Objects. However, sometimes you want to sort collections in-place, and as
IList<T> provides random access, there’s no reason we shouldn’t be able to. Now, I do like the way that OrderBy allows multiple criteria to be specified, whether they should be applied in an ascending or descending fashion, and by way of just “compare by this projection” rather than having to actually implement the comparison yourself. I thought I could probably make use of those ideas again.
Unlike in LINQ to Objects, the sort would occur immediately, which means I couldn’t use quite the chained syntax of
OrderBy(...).ThenBy(...).ThenByDescending(...) but my plan was to allow code like this:
myList.SortBy((person => person.Name).Ascending(),
(person => person.DateOfBirth).Descending(),
(person => person.SocialSecurityNumber).Ascending());
Because each of the different output types involved might be different, that would only work for as many overloads as I’d implement. An alternative would be:
.ThenByDescending(person => person.DateOfBirth)
.ThenBy(person => person.SocialSecurityNumber);
I did like the idea of the
Descending extension methods though, operating on
Func<T1,T2>. Unfortunately, the dot operator doesn’t work on lambda expressions, even though the expression itself is implicitly convertible to
My plan isn’t entirely scuppered – the latter syntax will still work, and there are probably some alternatives I can work out. I think there are nice possibilities around extension methods and delegates though, and it’s a shame they’re not useful for lambda expressions. Ah well.