Is there any way to negate a Predicate?

后端 未结 2 741
野性不改
野性不改 2020-12-18 17:52

I want to do something like this:

List list1 = ...
List list2 = ...
Predicate condition = ...

...

list2.         


        
2条回答
  •  一个人的身影
    2020-12-18 18:38

    You could use a lambda expression to define an anonymous delegate inplace that is the result of negating the result of the predicate:

    list.RemoveAll(x => !condition(x));    
    

    Another option:

    static Predicate Negate(Predicate predicate) {
         return x => !predicate(x);
    }
    

    Usage:

    // list is List some T
    // predicate is Predicate some T
    list.RemoveAll(Negate(predicate));
    

    The reason that list.RemoveAll(!condition) does not work is that there is no ! operator defined on delegates. This is why you must define a new delegate in terms of condition as shown above.

提交回复
热议问题