Nitriq is a product by


 
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.


Tuesday, May 11, 2010 - 4:16 PM CST - Permalink - Comments [3]
Tags: Tips and Tricks


Friday, May 14, 2010 7:37:48 AM (Central Standard Time, UTC-06:00)
I think it's important to realize what's going on behind the scenes here.

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

translates into something very close to

Categories
.Select(cat => new { cat, AvgPrice = cat.Products.Average(p => p.Price) })
.Where(x => x.AvgPrice < 100)
.Select(x => new { x.cat.Name, x.AvgPrice)

Which, as you can see, forms an anonymous object, which you can then query on and is nice and fast.
Monday, June 28, 2010 12:27:53 AM (Central Standard Time, UTC-06:00)
I agree with you. I’m a gamer myself and I play online games like Aion Online, WoW and EQ which we all know like console games will eventually be gone once the publisher decides to stop investing on the game. It will hurt real bad since the time, money and effort you invested will be gone in just a snap.
Monday, June 28, 2010 12:28:34 AM (Central Standard Time, UTC-06:00)
everybody,are you a world of warcraft player,are you wanna buy wow gold,Whether wow gold us or wow gold eu,wowruler.com will provide cheap and fast wow gold service for you,Website is very simple and Fast, You can buy wow gold coin in the very quick time, because we very dedicated.
Comments are closed.