views:

599

answers:

2

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?

+16  A: 

There's a good article here: http://gregbeech.com/blogs/tech/archive/2008/04/21/translating-c-3-0-query-syntax-for-linq-to-objects-part-4-let.aspx

Essentially let creates an anonymous tuple. It's equivalent to:

var result = names.Select(
  animal => new { animal = animal, nameLength = animal.Length })
.Where(x => x.nameLength > 3)
.OrderBy(y => y.nameLength)
.Select(z => z.animal);
Keltex
+1 Seemed kinda criminal that Marc had the only upvote!
Daniel Earwicker
+17  A: 

Let doesn't have its own operation; it piggy packs 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);
Marc Gravell
Woah, I didn't know you could autoencapsulate using the new operator like that.
David Pfeffer