Reuse of a LINQ query

前端 未结 4 538
梦谈多话
梦谈多话 2020-12-14 06:06

This is not about the reuse of a result but more the statement itself. Nor is it about an error when using var as mentioned in: LINQ to SQL: Reuse lambda expression

4条回答
  •  猫巷女王i
    2020-12-14 06:55

    It depends. There's two Where methods, Enumerable.Where and Queryable.Where. If you're applying the .Where to an IEnumerable than the first one is called, if you're applying it to an IQueryable the second one is called.

    Since Enumerable.Where takes in a Func, it isn't reusable. Since Queryable.Where takes in an expression, it is reusable. You can do so as follows:

    var x = new List().AsQueryable();
    
    var query = x.Where (n => n.Contains("some string"));
    
    //Extract the lambda clause
    var expr = query.Expression;
    var methodExpr = (MethodCallExpression)expr;
    var quoteExpr = (UnaryExpression)methodExpr.Arguments[1];
    var funcExpr = (Expression>)quoteExpr.Operand;
    

    You can then later re-apply the where expression:

    var query2 = x.Where(funcExpr);
    

提交回复
热议问题