Saw a post about hidden features in C# but not a lot of people have written linq/lambdas example so... I wonder...
What's the coolest (as in the most elegant) use of the C# LINQ and/or Lambdas/anonymous delegates you have ever saw/written?
Bonus if it has went into production too!
To me, the duality between delegates (
Func<T,R>
,Action<T>
) and expressions (Expression<Func<T,R>>
Expression<Action<T>>
) is what gives rise to the most clever uses of lambdas.For example:
Then you can "safely" implement
INotifyPropertyChanged
by callingNote : I saw this on the web at first a few weeks ago, then lost the link and a score of variations have cropped up here and there since then so I'm afraid I cannot give proper attribution.
OLINQ reactive LINQ queries over INotifyingCollection - these allow you to do (amongst other things) realtime aggregation against large datasets.
https://github.com/wasabii/OLinq
Not my design but I've used it a few times, a typed-switch statement: http://community.bartdesmet.net/blogs/bart/archive/2008/03/30/a-functional-c-type-switch.aspx
Saved me so many if... else if... else if... else IF! statements
I was trying to come up with a cool way to build a navigation control for a website I was building. I wanted to use regular HTML unordered list elements (employing the standard CSS "Sucker Fish" look) with a top-navigation mouse-over effect that reveals the drop down items. I had a sql dependent cached DataSet with two tables (NavigationTopLevels & NavigationBottomLevels). Then all I had to was create two class objects (TopNav & SubNav) with the few required properties (the TopNav class had to have a generic list of bottomnav items -> List<SubNav> SubItems).
It might not be the "coolest" but for a lot of people who want to have dynamic navigation, its sweet not to have to muddle around in the usual looping logic that comes with that. LINQ is, if anything a time saver in this case.
By far the most impressive Linq implementation i've ever come across is the Brahma framework.
It can be used to offload parallel calculations to the GPU using 'Linq to GPU'. You write a 'query' in linq, and then Brahma translates it into HLSL (High Level Shader Language) so DirectX can process it on the GPU.
This site will only let me paste one link so try this webcast from dotnetrocks:
http://www.dotnetrocks.com/default.aspx?showNum=466
Else google for Brahma Project, you'll get the right pages.
Extremely cool stuff.
GJ
Actually, I'm quite proud of this for generating Excel docments: http://www.aaron-powell.com/linq-to-xml-to-excel