LBushkin LBushkin - 8 months ago 43
C# Question

Code equivalent to the 'let' keyword in chained LINQ extension method calls

Using the C# compilers query comprehension features, you can write code like:

var names = new string[] { "Dog", "Cat", "Giraffe", "Monkey", "Tortoise" };
var result =
from animalName in names
let nameLength = animalName.Length
where nameLength > 3
orderby nameLength
select animalName;

In the query expression above, the
keyword allows a value to be passed forward to the where and orderby operations without duplicate calls to

What is the equivalent set of LINQ extension method calls that achieves what the "let" keyword does here?


Let doesn't have its own operation; it piggy-backs off of Select. You can see this if you use "reflector" to pull apart an existing dll.

it will be something like:

var result = names
        .Select(animalName => new { nameLength = animalName.Length, animalName})
        .Where(x=>x.nameLength > 3)