我如何从字符串制作动态Lambda表达式?

我如何从字符串制作动态Lambda表达式?

问题描述:

我需要在方法中使用Lambda表达式

I need use Lambda Expression in my method

public static class QueryableDynamicExtension
{
    public static IQueryable<T> DynamicEquals<T>(
       this IQueryable<T> query,
       string field,
       object value)
    {
        Expression<Func<T, bool>> expr = ???                   

        return query.Where(expr);
    }
}

在这种方法中,我希望它的返回结果与

In this method, I want it return same as

IQueryable<Article> articles = new ModelDataContext().Articles.Where(m => m.CategoryId == 5);
// I want replace by
IQueryable<Article> articles = new ModelDataContext().Articles.DynamicEquals("CategoryId", 5);

在这种情况下,我应该如何构建"expr"?请帮忙.

How should I build the "expr" in this case? Please help.

您可以将动态LINQ库作为

You could look into the Dynamic LINQ library, as blogged by Scott Gu here. I've used this previously where I've built a rules-based product system for work, and have used dynamic expressions stored in our database layer to provide additional expressions to filter out product sets.