How to excute a LINQ Expression

Linq for .NET 3.5 is a very interesting new feature. It provide you some abilities that compiler has.

Thanks for Expression (under System.Linq.Expressions namespace), we can keep the expression tree but not compiled MSIL code.

When you use Linq like this,

var count = from dataItem in data where dataItem.Value > 100 select data.Value2;

You do not need to know the expression tree (You even do not need to add the using of System.Linq.Expressions), .NET compiler and runtime to all the things for you.

That good most of the times.

Sometimes, you need to do something by yourself. Just like my current project, I need get the result directly from a expression tree.

object GetResult(Expression m);

T GetResult<T>(Expression m);

The only one I can find to do this directly is Excute method in IQueryProvider interface.

public interface IQueryProvider
Object Excute(Expression expression);

TResult Excute
(Expression expression);

Looks great, but useless. It use an interface, and I cannot find a impliment in the framework.

Ok, it’s time to show you the truth. No more words. Just the code below.

public static object GetResult(this Expression m)
    if (m == null)
        throw new ArgumentException("m");
    Type type = typeof (Func<>).MakeGenericType(m.Type);
    LambdaExpression lambda = Expression.Lambda(type, m);
    Delegate callback = lambda.Compile();
    object result = callback.DynamicInvoke();
    return result;

public static T GetResult<T>(this Expression m)
    if (m == null)
        throw new ArgumentNullException("m");
    Expression<Func<T>> lambda = Expression.Lambda<Func<T>>(m);
    Func<T> callback = lambda.Compile();
    T result = callback();
    return result;

Compile to MSIL at runtime, isn’t it cool?!


Tags: , ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: