Simplify, Shorten and Speed Up Your LINQ Statements with "Let"

Posted: 5/11/2010 9:16:57 PM

I've been writing a lot of LINQ statements lately while working on Nitriq and have come across a pretty cool LINQ keyword - "let". It allows you to specify an intermediate calculation that can be referenced multiple times else where in your LINQ statement, including the where and select clauses.

As you can see below, this is how a lot of LINQ statements are written - a calculation is done both in the where clause and in the select clause. This not only make the code large and ugly, if this calculation is CPU intensive, you get hit with a performance penalty because you are running the calculation twice!
 

var cheapCategories = from cat in Categories
                      where cat.Products.Average(p => p.Price) < 100
                     
select new { cat.Name, AvgPrice = cat.Products.Average(p => p.Price) };


However, if we use the let keyword, the code is shorter and the runtime only needs to execute the average calculation once.

var cheapCategories = from cat in Categories
                     
let AvgPrice = cat.Products.Average(p => p.Price)
                     
where AvgPrice < 100
                     
select new { cat.Name, AvgPrice };


While this is this is a small example, I promise the let keyword will help you tame the monster LINQ statements lurking in your code.



Tags: Tips and Tricks