linq to entities dynamic where子句为string

时间:2011-05-25 20:41:06

标签: c# linq-to-entities

我想通过向where子句提供字符串表达式,使用linq动态过滤数据。

例如:

string filterExpr = "it.City='London'"
var ret1 = Contex.Customers.Where(filterExpr);

我该如何做同样的事情,但这一次过滤某些字符串开头的数据?

如果无法实现使用字符串,我该如何构建适当的Lambda表达式?

(对我来说,能够按许多参数(OR / AND)进行过滤非常重要)

4 个答案:

答案 0 :(得分:2)

我认为您可能正在寻找的是Dynamic LINQ。 Scott Guthrie发布了这个:

http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

它没有使用lambda语法那么快,因为它们需要在运行时编译,但它可能是你的答案。

答案 1 :(得分:1)

Public Shared Function getFilterStartsWith(Of T)(ByVal param As ParameterExpression, ByVal prop As MemberExpression, ByVal arg As Object) As Expression
    Dim mi As MethodInfo = GetType(String).GetMethod("StartsWith", New Type() {GetType(String)}, Nothing)
    Return Expression.Lambda(Of Func(Of T, Boolean))(LambdaExpression.[Call](prop, mi, Expression.Constant(arg, GetType(String))), param)
End Function

在C#中:

public static Expression getFilterStartsWith<T>(ParameterExpression param, MemberExpression prop, object arg) {
    MethodInfo mi = typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) }, null);
    return Expression.Lambda<Func<T, bool>>(LambdaExpression.Call(prop, mi, Expression.Constant(arg, typeof(string))), param);
}

这是我在最近写的solution中用于startsWith的函数。事实证明这是一个巨大的痛苦,因为你不能使用Type变量作为ctype中的参数或vb中的DirectCast,并且你不能对一个对象和相同类型的可空对象进行linq比较。

答案 2 :(得分:0)

请试试这个:

var ret1 = contex.Customers.Where(x => x.it.City.StartsWith('l'));

HTH

答案 3 :(得分:0)

忘记&#34;魔术&#34;字符串,C#意味着强类型。 这样或那样你最终会得到一个列表,所以最好的方法是强力键入它们。

    public class Veg
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public bool Fruit { get; set; }
    }

    enum Mode
    {
        One,
        Two,
        Three
    }

    static void Main()
    {
        Mode mode = Mode.One;

        var data = new List<Veg>
        {
            new Veg{Id = 1, Name = "Apple", Fruit = true},
            new Veg{Id = 2, Name = "Carrot", Fruit = false}
        };

        var dataSelect = data.Where(w => (mode == Mode.One && w.Fruit) || //only fruits
                                         (mode == Mode.Two && !w.Fruit) || //only not fruits
                                         (mode == Mode.Three)); //all of it
    }
相关问题