Easy sorting with generics and anonymous methods#

Imagine a typed dataset of which you want to sort the rows in a special way according to a calculation on the column values. Sounds fairly complicated - but using the new generics and anonymous methods feature in C# Whidbey, it's pretty easy really:

MonitorItemData.MonitorItemsRow[] rows; // This array is already filled.
Array.Sort<MonitorItemData.MonitorItemsRow>( rows,
    delegate( MonitorItemData.MonitorItemsRow row1, MonitorItemData.MonitorItemsRow row2 )
    {
        // Calculate the absolute deviations of the individual monitor items.
        // Multiply by 10000 to increase the subtraction precision of the ints.
        int deviation1 = Math.Abs( 10000 * ( row1.ActualValue - row1.StandardValue ) / row1.StandardValue );
        int deviation2 = Math.Abs( 10000 * ( row2.ActualValue - row2.StandardValue ) / row2.StandardValue );

        // Sort descending according to the deviation.
        return deviation2 - deviation1;
    }
);

For the Array.Sort method, we're using a generic overload which takes a an array of the generic type T and a Comparison<T> delegate that can compare two instances of the generic type. But where is the Comparison delegate type mentioned? Nowhere - it's called type inference. So by looking at the signature on the anonymous method above, the compiler can make a well-educated "guess" about the type of the delegate and this baby will just compile and run. Cool? I think so!

Comments are closed.
All content © 2012, Jelle Druyts
On this page

Recent Photos
www.flickr.com
This is a Flickr badge showing public photos from Jelle Druyts. Make your own badge here.
Advertising
Top Picks
Statistics
Total Posts: 350
This Year: 0
This Month: 0
This Week: 0
Comments: 530
Archives
Sitemap
Disclaimer
This is my personal website, not my boss', not my mother's, and certainly not the pope's. My personal opinions may be irrelevant, inaccurate, boring or even plain wrong, I'm sorry if that makes you feel uncomfortable. But then again, you don't have to read them, I just hope you'll find something interesting here now and then. I'll certainly do my best. But if you don't like it, go read the pope's blog. I'm sure it's fascinating.

Powered by:
newtelligence dasBlog 2.0.7226.0

Sign In