LINQ let Keyword


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.

Also with let query clauses, you can introduce a variable into scope and use it in the subsequent query clauses. Similar to local variables in a method body, this gives you a way to avoid evaluating a common expression multiple times by storing it in a variable.

For instance, inexperienced Linq developer quickly codes up a query that looks like this:

var nameList = new List<string>
var vowels = new List<string> {"A", "E", "I", "O", "U"};
var names = (from p in nameList                                                  
            (vowels.Any(v => p.ToUpper().StartsWith(v)) 
            || vowels.Any(v => p.ToUpper().EndsWith(v))) &&
            (p.Length == 4 
            || p.Length == 5)
            select p).ToList();


Using “let”, we can define four intermediate variables that hold our vowels and booleans for our tests, then in the where clause we just check our boolean values:

var names = (from p in nameList
            let vowels = new List<string> { "A", "E", "I", "O", "U" }
            let startsWithVowel = vowels.Any(v => p.ToUpper().StartsWith(v))
            let endsWithVowel = vowels.Any(v => p.ToUpper().EndsWith(v))
            let fourCharactersLong = p.Length == 4
            let fiveCharactersLong = p.Length == 5
            (startsWithVowel || endsWithVowel) &&
            (fourCharactersLong || fiveCharactersLong)
            select p).ToList();
About these ads

4 thoughts on “LINQ let Keyword

  1. And we can get exactly the same without let:

    var query = from i in list
    select new { i, j = i+2, k=i-2 };

    But let is really helpful in any other situations :o)

  2. Pingback: LINQ “Any” Keyword to check for existence of an element/attribute « vincenthome’s Tech Clips

  3. Pingback: Live Streaming Κάλυψη Συνεδρείων

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s