Welcome to SpellCoder Sign in | Join | Help

LINQ let Keyword (How did I miss that)

This is strange, because I've been working with LINQ for almost 2 years since (March 2006 CTP), and I've never noticed the new keyword "let" which is used inside LINQ queries to create temporarily variables.

check this out

var list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var query = from i in list
            let j = i + 2
            let k = j * j
            select new { i, j, k };

As you can see the let keyword was used to create two new temp variables (j, k) which their values were calculated inside the query.

Looks nice, doesn't it

kick it on DotNetKicks.com
Published Sunday, December 16, 2007 8:57 PM by Mohammed Hossam

Comments

# re: LINQ let Keyword (How did I miss that)

Wednesday, December 19, 2007 5:31 PM by Leon
I want to show 1 product per category from products and categories tables.

After using let, I got error:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

Any way to do this?

Many thanks

# re: LINQ let Keyword (How did I miss that)

Thursday, December 20, 2007 8:40 PM by Paul Stovell
The reason "let" wasn't obvious was that it's actually just another version of the "Select" enumerable - when you use "let", it performs a Select returning the original inputs plus the value of the let statement as a new object.

The best way to see this is to view the generated code in reflector.
Anonymous comments are disabled