C# Linq: Combine multiple .Where() with an *OR* clause

后端 未结 4 2126
不思量自难忘°
不思量自难忘° 2021-02-19 00:08

I have been searching a lot about my current problem but I could not find a real answer to solve that issue.

I am trying to build a LINQ Query that produces the followi

4条回答
  •  离开以前
    2021-02-19 00:55

    First, create some helper extension methods to easier combine two Func predicates:

     public static Func And(this Func left, Func right) 
         => a => left(a) && right(a);
    
     public static Func Or(this Func left, Func right)
         => a => left(a) || right(a);
    

    Then you can use them to chain predicates:

    var list = Enumerable.Range(1, 100);
    
    Func predicate = v => true; // start with true since we chain ANDs first
    
    predicate = predicate.And(v => v % 2 == 0); // numbers dividable by 2
    predicate = predicate.And(v => v % 3 == 0); // numbers dividable by 3
    predicate = predicate.Or(v => v % 31 == 0); // numbers dividable by 31
    
    var result = list.Where(predicate);
    
    foreach (var i in result)
        Console.WriteLine(i);
    

    Output:

    6
    12
    18
    24
    30
    31
    36
    42
    48
    54
    60
    62
    66
    72
    78
    84
    90
    93
    96
    

提交回复
热议问题