Adding OR expressions in a loop in Linq

后端 未结 3 1185
死守一世寂寞
死守一世寂寞 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:43

      public static IEnumerable GetItemsThatMatchAny (this IEnumerable source, IEnumerable> predicates)
        {      
          return source.Where(t => predicates.Any(predicate => predicate(t)));
        }
    

    An example of a predicate generator:

    private static IEnumerable> GetPredicates (int num)
    {
       var predicates = new Func[] {m => m.Foo == 3, m => m.Bar =="x", m => DateTime.Now.DayOfWeek == DayOfWeek.Sunday};
    
       return predicates.Take (num);
    }
    

提交回复
热议问题