Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Query Syntax to Lambda

Tags:

c#

linq

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.

like image 908
andleer Avatar asked Apr 29 '09 21:04

andleer


People also ask

What is lambda expression in LINQ?

A lambda expression is a convenient way of defining an anonymous (unnamed) function that can be passed around as a variable or as a parameter to a method call. Many LINQ methods take a function (called a delegate) as a parameter.

How do you convert this method into a lambda expression?

To convert an anonymous method to a lambda expressionMove to the anonymous method you want to convert. From the Refactor menu of the VisualAid choose To Lambda. Telerik® JustCode™ will replace the anonymous method with a lambda expression.

What is the basic structure syntax of a lambda expression?

Java Lambda Expression Syntax Java lambda expression is consisted of three components. 1) Argument-list: It can be empty or non-empty as well. 2) Arrow-token: It is used to link arguments-list and body of expression. 3) Body: It contains expressions and statements for lambda expression.


2 Answers

Simply go:

string lambdaSyntax = query.Expression.ToString();

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

like image 148
Joe Albahari Avatar answered Oct 22 '22 21:10

Joe Albahari


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 :-)

like image 39
Orion Edwards Avatar answered Oct 22 '22 19:10

Orion Edwards