Combine Multiple Predicates

后端 未结 7 726
眼角桃花
眼角桃花 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:18

    How about:

    public static Predicate Or(params Predicate[] predicates)
    {
        return delegate (T item)
        {
            foreach (Predicate predicate in predicates)
            {
                if (predicate(item))
                {
                    return true;
                }
            }
            return false;
        };
    }
    

    And for completeness:

    public static Predicate And(params Predicate[] predicates)
    {
        return delegate (T item)
        {
            foreach (Predicate predicate in predicates)
            {
                if (!predicate(item))
                {
                    return false;
                }
            }
            return true;
        };
    }
    

    Then call it with:

    List filteredNames = names.FindAll(Helpers.Or(StartsWithE, StartsWithI));
    

    Another alternative would be to use multicast delegates and then split them using GetInvocationList(), then do the same thing. Then you could do:

    List filteredNames = names.FindAll(Helpers.Or(StartsWithE+StartsWithI));
    

    I'm not a huge fan of the latter approach though - it feels like a bit of an abuse of multicasting.

提交回复
热议问题