有没有什么办法来否定一个predicate? [英] Is there any way to negate a Predicate?
问题描述
我想做的事情是这样的:
I want to do something like this:
List<SomeClass> list1 = ...
List<SomeClass> list2 = ...
Predicate<SomeClass> condition = ...
...
list2.RemoveAll (!condition);
...
list2.AddRange (list1.FindAll (condition));
不过,这将导致一个编译器错误,因为
不能适用于 predicate&LT;!SomeClass的&GT;
。有没有办法做到这一点?
However, this results in a compiler error, as !
can't be applied to Predicate<SomeClass>
. Is there any way to do this?
推荐答案
您可以使用lambda EX pression定义一个匿名委托就地是否定的predicate结果的结果:
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<T> Negate<T>(Predicate<T> predicate) {
return x => !predicate(x);
}
用法:
// list is List<T> some T
// predicate is Predicate<T> some T
list.RemoveAll(Negate(predicate));
这是 list.RemoveAll(!条件)
不工作的原因是没有定义!
运营商与会代表。这就是为什么你必须在条件
如上图所示。
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.
这篇关于有没有什么办法来否定一个predicate?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!