<p>Saw a post about hidden features in C# but not a lot of people have written linq/lambdas example so... I wonder...</p>

<blockquote>
  <p>What's the coolest (as in the most elegant) use of the C# LINQ and/or Lambdas/anonymous delegates you have ever saw/written?</p>
</blockquote>

<p>Bonus if it has went into production too!</p>

[{'answer_id': 28867, 'author': 'Markus Olsson', 'author_id': 2114, 'author_profile': 'https://Stackoverflow.com/users/2114', 'pm_score': 5, 'selected': False, 'text': '<p>The <a href="http://blogs.msdn.com/lukeh/archive/2007/10/01/taking-linq-to-objects-to-extremes-a-fully-linqified-raytracer.aspx" rel="noreferrer">LINQ Raytracer</a> certainly tops my list =)</p>\n\n<p>I\'m not quite sure if qualifies as elegant but it is most certainly the coolest linq-expression I\'ve ever seen!</p>\n\n<p>Oh, and just to be extremely clear; I did <em>not</em> write it (<a href="http://blogs.msdn.com/lukeh/" rel="noreferrer">Luke Hoban</a> did)</p>\n'}, {'answer_id': 28883, 'author': 'Ian Patrick Hughes', 'author_id': 2213, 'author_profile': 'https://Stackoverflow.com/users/2213', 'pm_score': 1, 'selected': False, 'text': '<p>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 <a href="http://www.alistapart.com/articles/dropdowns" rel="nofollow noreferrer">CSS "Sucker Fish" look</a>) with a top-navigation mouse-over effect that reveals the drop down items. I had a sql dependent cached DataSet with two tables (NavigationTopLevels &amp; NavigationBottomLevels). Then all I had to was create two class objects (TopNav &amp; SubNav) with the few required properties (the TopNav class had to have a generic list of bottomnav items -> List&lt;SubNav&gt; SubItems).</p>\n\n<pre>\n<br>\nvar TopNavs = from n in ds.NavigationTopLevels\n                          select new TopNav\n                          {\n                              NavigateUrl = String.Format("{0}/{1}", tmpURL, n.id),\n                              Text = n.Text,\n                              id = n.id,\n                              SubItems = new List&lt;SubNav&gt;(\n                                  from si in ds.NavigationBottomLevels\n                                  where si.parentID == n.id\n                                  select new SubNav\n                                  {\n                                      id = si.id,\n                                      level = si.NavLevel,\n                                      NavigateUrl = String.Format("{0}/{1}/{2}", tmpURL, n.id, si.id),\n                                      parentID = si.parentID,\n                                      Text = si.Text\n                                  }\n                                )\n\n                          };\n\n List&lt;TopNav&gt; TopNavigation = TopNavs.ToList(); \n<br>\n</pre>\n\n<p>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.\n<br></p>\n'}, {'answer_id': 28920, 'author': 'Drakiula', 'author_id': 2437, 'author_profile': 'https://Stackoverflow.com/users/2437', 'pm_score': 2, 'selected': False, 'text': '<p><a href="http://igoro.com/archive/extended-linq-additional-operators-for-linq-to-objects/" rel="nofollow noreferrer">http://igoro.com/archive/extended-linq-additional-operators-for-linq-to-objects/</a></p>\n\n<p><a href="http://igoro.com/archive/7-tricks-to-simplify-your-programs-with-linq/" rel="nofollow noreferrer">http://igoro.com/archive/7-tricks-to-simplify-your-programs-with-linq/</a></p>\n'}, {'answer_id': 28973, 'author': 'Chris Ammerman', 'author_id': 2729, 'author_profile': 'https://Stackoverflow.com/users/2729', 'pm_score': 4, 'selected': False, 'text': '<p>Some basic functionals:</p>\n\n<pre><code>public static class Functionals\n{\n    // One-argument Y-Combinator.\n    public static Func&lt;T, TResult&gt; Y&lt;T, TResult&gt;(Func&lt;Func&lt;T, TResult&gt;, Func&lt;T, TResult&gt;&gt; F)\n    {\n        return t =&gt; F(Y(F))(t);\n    }\n\n    // Two-argument Y-Combinator.\n    public static Func&lt;T1, T2, TResult&gt; Y&lt;T1, T2, TResult&gt;(Func&lt;Func&lt;T1, T2, TResult&gt;, Func&lt;T1, T2, TResult&gt;&gt; F)\n    {\n        return (t1, t2) =&gt; F(Y(F))(t1, t2);\n    }\n\n    // Three-arugument Y-Combinator.\n    public static Func&lt;T1, T2, T3, TResult&gt; Y&lt;T1, T2, T3, TResult&gt;(Func&lt;Func&lt;T1, T2, T3, TResult&gt;, Func&lt;T1, T2, T3, TResult&gt;&gt; F)\n    {\n        return (t1, t2, t3) =&gt; F(Y(F))(t1, t2, t3);\n    }\n\n    // Four-arugument Y-Combinator.\n    public static Func&lt;T1, T2, T3, T4, TResult&gt; Y&lt;T1, T2, T3, T4, TResult&gt;(Func&lt;Func&lt;T1, T2, T3, T4, TResult&gt;, Func&lt;T1, T2, T3, T4, TResult&gt;&gt; F)\n    {\n        return (t1, t2, t3, t4) =&gt; F(Y(F))(t1, t2, t3, t4);\n    }\n\n    // Curry first argument\n    public static Func&lt;T1, Func&lt;T2, TResult&gt;&gt; Curry&lt;T1, T2, TResult&gt;(Func&lt;T1, T2, TResult&gt; F)\n    {\n        return t1 =&gt; t2 =&gt; F(t1, t2);\n    }\n\n    // Curry second argument.\n    public static Func&lt;T2, Func&lt;T1, TResult&gt;&gt; Curry2nd&lt;T1, T2, TResult&gt;(Func&lt;T1, T2, TResult&gt; F)\n    {\n        return t2 =&gt; t1 =&gt; F(t1, t2);\n    }\n\n    // Uncurry first argument.\n    public static Func&lt;T1, T2, TResult&gt; Uncurry&lt;T1, T2, TResult&gt;(Func&lt;T1, Func&lt;T2, TResult&gt;&gt; F)\n    {\n        return (t1, t2) =&gt; F(t1)(t2);\n    }\n\n    // Uncurry second argument.\n    public static Func&lt;T1, T2, TResult&gt; Uncurry2nd&lt;T1, T2, TResult&gt;(Func&lt;T2, Func&lt;T1, TResult&gt;&gt; F)\n    {\n        return (t1, t2) =&gt; F(t2)(t1);\n    }\n}\n</code></pre>\n\n<p>Don\'t do much good if you don\'t know how to use them.  In order to know that, you need to know what they\'re for:</p>\n\n<ul>\n<li><a href="https://stackoverflow.com/questions/36314/what-is-currying">What is currying?</a></li>\n<li><a href="https://stackoverflow.com/questions/93526/what-is-a-y-combinator">What is a y-combinator?</a></li>\n</ul>\n'}, {'answer_id': 81304, 'author': 'Samuel Jack', 'author_id': 1727, 'author_profile': 'https://Stackoverflow.com/users/1727', 'pm_score': 4, 'selected': False, 'text': '<p><a href="http://blog.functionalfun.net/2008/07/reporting-progress-during-linq-queries.html" rel="noreferrer">Progress Reporting</a> for long running LINQ queries. In the blog post you can find an extension method WithProgressReporting() that lets you discover and report the progress of a linq query as it executes.</p>\n'}, {'answer_id': 81331, 'author': 'Aaron Powell', 'author_id': 11388, 'author_profile': 'https://Stackoverflow.com/users/11388', 'pm_score': 2, 'selected': False, 'text': '<p>Not my design but I\'ve used it a few times, a typed-switch statement: <a href="http://community.bartdesmet.net/blogs/bart/archive/2008/03/30/a-functional-c-type-switch.aspx" rel="nofollow noreferrer">http://community.bartdesmet.net/blogs/bart/archive/2008/03/30/a-functional-c-type-switch.aspx</a></p>\n\n<p>Saved me so many if... else if... else if... else IF! statements</p>\n'}, {'answer_id': 81382, 'author': 'ThatBloke', 'author_id': 7050, 'author_profile': 'https://Stackoverflow.com/users/7050', 'pm_score': 1, 'selected': False, 'text': "<p>I think that LINQ is a major change to .NET and it is a very powerful tool.<br>\n<br>\nI use LINQ to XML in production to parse and filter records from a 6MB XML file (with 20+ node levels) into a dataset in two lines of code.<br>\n<br>\nBefore LINQ this would have taken hundreds of lines of code and days to debug.\n<br>\n<br>\nThat's what I call elegant!</p>\n"}, {'answer_id': 81498, 'author': 'Aaron Powell', 'author_id': 11388, 'author_profile': 'https://Stackoverflow.com/users/11388', 'pm_score': 2, 'selected': False, 'text': '<p>Actually, I\'m quite proud of this for generating Excel docments: <a href="http://www.aaron-powell.com/linq-to-xml-to-excel" rel="nofollow noreferrer">http://www.aaron-powell.com/linq-to-xml-to-excel</a></p>\n'}, {'answer_id': 311750, 'author': 'Bryan Watts', 'author_id': 37815, 'author_profile': 'https://Stackoverflow.com/users/37815', 'pm_score': 0, 'selected': False, 'text': '<p>Working with attributes:</p>\n\n<pre><code>private void WriteMemberDescriptions(Type type)\n{\n    var descriptions =\n        from member in type.GetMembers()\n        let attributes = member.GetAttributes&lt;DescriptionAttribute&gt;(true)\n        let attribute = attributes.FirstOrDefault()\n        where attribute != null\n        select new\n        {\n            Member = member.Name,\n            Text = attribute.Description\n        };\n\n        foreach(var description in descriptions)\n        {\n            Console.WriteLine("{0}: {1}", description.Member, description.Text);\n        }\n}\n</code></pre>\n\n<p>The <code>GetAttributes</code> extension method:</p>\n\n<pre><code>public static class AttributeSelection\n{\n    public static IEnumerable&lt;T&gt; GetAttributes&lt;T&gt;(this ICustomAttributeProvider provider, bool inherit) where T : Attribute\n    {\n        if(provider == null)\n        {\n            throw new ArgumentNullException("provider");\n        }\n\n        return provider.GetCustomAttributes(typeof(T), inherit).Cast&lt;T&gt;();\n    }\n}\n</code></pre>\n\n<p><code>AttributeSelection</code> is production code and also defines <code>GetAttribute</code> and <code>HasAttribute</code>. I chose to use the <code>let</code> and <code>where</code> clauses in this example.</p>\n'}, {'answer_id': 324880, 'author': 'Tomas Petricek', 'author_id': 33518, 'author_profile': 'https://Stackoverflow.com/users/33518', 'pm_score': 2, 'selected': False, 'text': '<p>I did one (a bit crazy, but interesting) thing like that just recently:</p>\n\n<ul>\n<li><a href="http://tomasp.net/blog/reactive-iv-reactivegame.aspx" rel="nofollow noreferrer">http://tomasp.net/blog/reactive-iv-reactivegame.aspx</a></li>\n</ul>\n'}, {'answer_id': 1294663, 'author': 'gjvdkamp', 'author_id': 65747, 'author_profile': 'https://Stackoverflow.com/users/65747', 'pm_score': 4, 'selected': False, 'text': '<p>By far the most impressive Linq implementation i\'ve ever come across is the Brahma framework.</p>\n\n<p>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.</p>\n\n<p>This site will only let me paste one link so try this webcast from dotnetrocks:</p>\n\n<p><a href="http://www.dotnetrocks.com/default.aspx?showNum=466" rel="noreferrer">http://www.dotnetrocks.com/default.aspx?showNum=466</a></p>\n\n<p>Else google for Brahma Project, you\'ll get the right pages.</p>\n\n<p>Extremely cool stuff.</p>\n\n<p>GJ</p>\n'}, {'answer_id': 1296623, 'author': 'Thomas Dufour', 'author_id': 371593, 'author_profile': 'https://Stackoverflow.com/users/371593', 'pm_score': 2, 'selected': False, 'text': '<p>To me, the duality between delegates (<code>Func&lt;T,R&gt;</code>, <code>Action&lt;T&gt;</code>) and expressions (<code>Expression&lt;Func&lt;T,R&gt;&gt;</code> <code>Expression&lt;Action&lt;T&gt;&gt;</code>) is what gives rise to the most clever uses of lambdas.</p>\n\n<p>For example:</p>\n\n<pre><code>public static class PropertyChangedExtensions\n{\n    public static void Raise(this PropertyChangedEventHandler handler, Expression&lt;Func&lt;object&gt;&gt; propertyExpression)\n    {\n        if (handler != null)\n        {\n            // Retrieve lambda body\n            var body = propertyExpression.Body as MemberExpression;\n            if (body == null)\n                throw new ArgumentException("\'propertyExpression\' should be a member expression");\n\n            // Extract the right part (after "=&gt;")\n            var vmExpression = body.Expression as ConstantExpression;\n            if (vmExpression == null)\n                throw new ArgumentException("\'propertyExpression\' body should be a constant expression");\n\n            // Create a reference to the calling object to pass it as the sender\n            LambdaExpression vmlambda = Expression.Lambda(vmExpression);\n            Delegate vmFunc = vmlambda.Compile();\n            object vm = vmFunc.DynamicInvoke();\n\n            // Extract the name of the property to raise a change on\n            string propertyName = body.Member.Name;\n            var e = new PropertyChangedEventArgs(propertyName);\n            handler(vm, e);\n        }\n    }\n}\n</code></pre>\n\n<p>Then you can "safely" implement <code>INotifyPropertyChanged</code> by calling</p>\n\n<pre><code>if (PropertyChanged != null)\n    PropertyChanged.Raise( () =&gt; MyProperty );\n</code></pre>\n\n<p>Note : 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.</p>\n'}, {'answer_id': 2729591, 'author': 'Krisc', 'author_id': 299946, 'author_profile': 'https://Stackoverflow.com/users/299946', 'pm_score': 1, 'selected': False, 'text': '<p>Perhaps not the coolest, but recently I have been using them anytime I have a block of code that gets C+Pd over and over again only to have a few lines change. For instance, running simple SQL commands to retrieve data can be done like so:</p>\n\n<pre><code>SqlDevice device = GetDevice();\n\nreturn device.GetMultiple&lt;Post&gt;(\n    "GetPosts",\n    (s) =&gt; {\n        s.Parameters.AddWithValue("@CreatedOn", DateTime.Today);\n\n        return true;\n    },\n    (r, p) =&gt; {\n        p.Title = r.Get&lt;string&gt;("Title");\n\n        // Fill out post object\n\n        return true;\n    }\n);\n</code></pre>\n\n<p>Which could return a list of Posts that were created today. This way I don\'t have to copy and paste the try-catch-finally block fifteen million times for each command, object, et cetera.</p>\n'}, {'answer_id': 18486144, 'author': 'mcintyre321', 'author_id': 2086, 'author_profile': 'https://Stackoverflow.com/users/2086', 'pm_score': 0, 'selected': False, 'text': '<p>OLINQ reactive LINQ queries over INotifyingCollection - these allow you to do (amongst other things) realtime aggregation against large datasets.</p>\n\n<p><a href="https://github.com/wasabii/OLinq" rel="nofollow">https://github.com/wasabii/OLinq</a></p>\n'}]
['https://Stackoverflow.com/questions/28858', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3055/']