Monday, May 19, 2008

Linq OrderBy Descending fun

So for a few days I've been playing with Linq with production code and it looked great and (at least the usual stuff) pretty straightforward.
The underlying c# is scary of course, reminding me of the nightmare from the C++ generics/COM days. But at least now the IDE has evolved and IntelliSense works nicely.

Anyway - I came to the point were some tweaking was needed and some parametrizing - mainly i needed the order by to be runtime desided - 'dynamic' if you wish - so i started reading around blogs and sample code, but all seem to be aiming too high and I didn't have much time to really dive into Linq (which I should do someday anyway)... still quantity changes lead to some understanding of the problem in question , mostly after looking at (not really reading) samples at http://www.ddj.com/database/205604421, http://srtsolutions.com/blogs/billwagner/archive/2006/03/29/ordering-linq-results.aspx
and http://community.bartdesmet.net/blogs/bart/archive/2008/04/27/q-is-iqueryable-the-right-choice-for-me.aspx

I came up with this really small snippet of code that solved easily my problem



public static OrderedEnumerableRowCollection
OrderByEnhanced
(this EnumerableRowCollection source, Func keySelector, bool ASC)
{
if (ASC)
return source.OrderBy(keySelector);
else
return source.OrderByDescending(keySelector);
}




ain't it funny - it is so simple, but looking for a solution to my problem lead me to reading a lot about Linq and helped me learn a lot too, so that time was not waisted, so to say

cha!