Combine Multiple Predicates

后端 未结 7 729
眼角桃花
眼角桃花 2020-12-01 03:32

Is there any way in c# .NET 2.0! to combine multiple Predicates?

Let\'s say I have the following code.

List names = new List

        
7条回答
  •  甜味超标
    2020-12-01 04:17

    I just recently came up with a solution similar to this problem, which could be also helpful. I expanded the FindAll method for lists, allowing me to stack predicates in lists as I needed:

    public static class ExtensionMethods
    {
        public static List FindAll (this List list, List> predicates)
        {
            List L = new List ();
            foreach (T item in list)
            {
                bool pass = true;
                foreach (Predicate p in predicates)
                {
                    if (!(p (item)))
                    {
                        pass = false;
                        break;
                    }
                }
                if (pass) L.Add (item);
            }
            return L;
        }
    }
    

    It returns a list with only the items matching all given predicates. Of course it can easily be altered to OR all predicates instead of AND. But with that alone one can assemble quite a good variety of logical combinations.

    Usage:

    {
        List> P = new List> ();
        P.Add (j => j > 100);
        P.Add (j => j % 5 == 0 || j % 7 == 0);
        P.Add (j => j < 1000);
    
        List L = new List () { 0, 1, 2, ... 999, 1000 }
        List result = L.FindAll (P);
    
        // result will contain: 105, 110, 112, 115, 119, 120, ... 994, 995 
    }
    

提交回复
热议问题