Adding OR expressions in a loop in Linq

后端 未结 3 1188
死守一世寂寞
死守一世寂寞 2021-02-05 19:17

I have a variable number of OR conditions that I want to put together into one Linq query.

How do I do this in a loop? Basically, the final query is to

3条回答
  •  情书的邮戳
    2021-02-05 19:36

    A less-than-optimized version (pray that the backend will do the necessary lifting and optimization).

    public static IQueryable Any(this IQueryable q, 
      params Expression>[] preds)
    {
      var par = Expression.Parameter(typeof(T), "x");
    
      Expression body = Expression.Constant(false);
    
      foreach (var pred in preds)
      {
        body = Expression.OrElse(body, Expression.Invoke(pred, par));
      }
    
      var ff = Expression.Lambda(body, par) as Expression>;
    
      return q.Where(ff);
    }
    
    static void Main(string[] args)
    {
      var q = new[] { "jim", "bob", "Jon", "leppie" }.AsQueryable();
    
      Expression>[] preds =
      {
        x => x == "Jon",
        x => x == "Skeet",
        x => x == "leppie"
      };
    
      var result = q.Any(preds).ToArray();
    }
    

提交回复
热议问题