Using LET in LINQ with extension method syntax

Security Briefs

Syndication

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.

It’s not often I need LET, but when I do, I’ll be glad I jotted this down.


Posted Oct 07 2009, 10:53 AM by keith-brown

Comments

Ryan Dunn wrote re: Using LET in LINQ with extension method syntax
on 10-07-2009 12:48 PM

Even easier - use Linqpad:

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

IEnumerable<string> results =

from s in input.AsQueryable()

let x = s.Length

select string.Format("{0} ({1})", s, x);

results.Dump();

Just click the little 'lamda' icon and it shows the syntax.  Best tool ever.

keith-brown wrote re: Using LET in LINQ with extension method syntax
on 10-07-2009 1:19 PM

Thanks, Ryan for the pointer. I've heard of Linqpad before but hadn't tried it. Just gave it a whirl and after figuring out that I needed to switch "Language" to "C# Statements", it ran and showed me results just fine.

But clicking the lamda icon showed blank results. Did you get this to work?

I'm using Linqpad v1.35.3, which I just downloaded.

Ryan Dunn wrote re: Using LET in LINQ with extension method syntax
on 10-07-2009 3:21 PM

Sure.  You just need to make sure that the expression is IQueryable.  Notice in my snippet above that I used AsQueryable().

keith-brown wrote re: Using LET in LINQ with extension method syntax
on 10-07-2009 3:35 PM

D'oh - missed that thanks.