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?
There is also a .Let extension method in System.Interactive, but its purpose is to introduce a lambda expression to be evaluated 'in-line' in a fluent expression. For instance, consider (in LinqPad, say) the following expression that creates new random numbers every time it's executed:
To see that new random samples show up every time, consider the following
which produces pairs in which the left and right are different. To produce pairs in which the left and right are always the same, do something like the following:
If we could invoke lambda expressions directly, we might write
But we can't invoke lambda expressions as if they were methods.
There's a good article here
Essentially
let
creates an anonymous tuple. It's equivalent to: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: