How to Use Let in LINQ Extension Methods

For a variety of reasons (many of which Scott Allen discusses in his wonderful LINQ course), I prefer to use extension method syntax with LINQ instead of query expression syntax. But one thing I miss is the “let” operation that allows me to compute intermediate results and store them in a new variable.

This morning I came across a case where this would really simplify things, so I sat down to remember how to do it (I know I’ve done it before but I couldn’t remember the trick). So I wrote the simplest query I could think of using LET…

string[] input = { "asdf", "asd", "as", "a" };

IEnumerable<string> results =
    from s in input
    let x = s.Length
    select string.Format("{0} ({1})", s, x);

Print(results);

…and looked at it with RedGate Reflector, and remembered how I’d done this before – by introducing an enveloping anonymous type. Here’s the equivalent using extension methods:

results = input
    .Select(s => new { s = s, x = s.Length })
    .Select(e => string.Format("{0} ({1})", e.s, e.x));

Both of these queries produce the same results:

asdf (4)
asd (3)
as (2)
a (1)

There’s an object being processed in the pipeline – in this case it’s a string. The trick is to envelope that object with an anonymous type so that you can add one or more sibling variables that travel with it through the pipeline. The variable “e” in this example is the envelope.

share save 171 16 How to Use Let in LINQ Extension Methods

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

Tags: , , ,

Leave a Reply