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

LBushkin picture LBushkin · Jul 7, 2009 · Viewed 48.5k times · Source

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 let keyword allows a value to be passed forward to the where and orderby operations without duplicate calls to animalName.Length.

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

Answer

Marc Gravell picture Marc Gravell · Jul 7, 2009

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)
        .OrderBy(x=>x.nameLength)
        .Select(x=>x.animalName);