9

Wondering if there is any way to get the lambda expressions that result from a LINQ "query" syntax expression.

Given:

var query = from c in dc.Colors
            where c.ID == 213
            orderby c.Name, c.Description
            select new {c.ID, c.Name, c.Description };

Is there any way to get the generated "lambda" code / expression?

var query = dc.Colors
    .Where(c => c.ID == 213)
    .OrderBy(c => c.Name)
    .ThenBy(c => c.Description)
    .Select(c => new {c.ID, c.Name, c.Description, });

I know these are very simple examples and that the C# compiler generates a lambda expression from the query expression when compiling the code. Is there any way to get a copy of that expression?

I am hoping to use this as a training tool for some of my team members that aren't very comfortable with lambda expressions. Also, I have used Linq Pad, but ideally this can be accomplised without a 3rd party tool.

3 Answers 3

5

Simply go:

string lambdaSyntax = query.Expression.ToString();

The disadvantage compared to LINQPad is that the result is formatted all one line.

4
  • This produces similar results to those found by using Reflector on your assembly. All static method calls against crazy named anonymous types. Not ideal.
    – andleer
    Commented May 1, 2009 at 17:26
  • It's better than what you see in Reflector - and it's as good as you'll get without third party tools. Commented May 9, 2009 at 10:45
  • Love your book. I bought a few copies for team members.
    – andleer
    Commented Feb 2, 2010 at 15:38
  • I believe from some tests that you need to make sure query is Queryable. You can do this by adding .AsQueryable() to the first enumerable if needed.
    – Chris
    Commented Aug 9, 2012 at 12:01
3

You could try compiling the assembly and then having a look at it using Reflector.

This might be a bit more complicated than you want though, because the compiler will compile things right down to the direct method calls (everything will be static method calls, not extension methods, and the lambdas will get compiled into their own functions which are usually called something like <ClassName>b_88f)

You'll certainly figure out what's going on though :-)

1
  • Reflector is a wonderful tool! Bonus points because you can use it to look at the .net code for just about any .net assembly. Commented May 1, 2009 at 1:27
2

ReSharper has that feature. It will take a LINQ to Lambda and back again at the stroke of a key. Also very (very) useful for other things.

1
  • Really trying to avoid 3rd party tools.
    – andleer
    Commented Apr 30, 2009 at 3:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.