LINQ Select Dynamic Columns and Values

前端 未结 5 1358
别跟我提以往
别跟我提以往 2020-12-15 09:58

For various reasons I need to be able to allow the user to select an item from a database based on their choice of columns and values. For instance, if I have a table:

5条回答
  •  粉色の甜心
    2020-12-15 10:11

    Fine. Let me give my two cents. If you want to use dynamic LINQ, expression trees should be your option. You can generate LINQ statements as dynamic as you want. Something like following should do the magic.

    // inside a generic class.
    public static IQueryable GetWhere(string criteria1, string criteria2, string criteria3, string criteria4)
    {
        var t = MyExpressions.DynamicWhereExp(criteria1, criteria2, criteria3, criteria4);
        return db.Set().Where(t);
    }
    

    Now in another generic class you can define your expressions as.

    public static Expression> DynamicWhereExp(string criteria1, string criteria2, string criteria3, string criteria4)
    {
        ParameterExpression Param = Expression.Parameter(typeof(T));
    
        Expression exp1 = WhereExp1(criteria1, criteria2, Param);
        Expression exp2 = WhereExp1(criteria3, criteria4, Param);
    
        var body = Expression.And(exp1, exp2);
    
        return Expression.Lambda>(body, Param);
    }
    
    private static Expression WhereExp1(string field, string type, ParameterExpression param) 
    {
        Expression aLeft = Expression.Property(param, typeof(T).GetProperty(field));
        Expression aRight = Expression.Constant(type);
        Expression typeCheck = Expression.Equal(aLeft, aRight);
        return typeCheck;   
    }
    

    Now you can call the methods anywhere as.

    // get search criterias from user
    var obj = new YourClass();
    var result = obj.GetWhere(criteria1, criteria2, criteria3, criteria4);
    

    This will give you a powerfully dynamic expression with two conditions with AND operator between them to use in your where extension method of LINQ. Now you can pass your arguments as you want based on your strategy. e.g. in params string[] or in key value pair list... doesn't matter.

    You can see that nothing is fixed here.. its completely dynamic and faster than reflection and you an make as many expressions and as many criterias...

提交回复
热议问题