有什么办法可以否定谓词吗?
我想做这样的事情:
List<SomeClass> list1 = ...
List<SomeClass> list2 = ...
Predicate<SomeClass> condition = ...
...
list2.RemoveAll (!condition);
...
list2.AddRange (list1.FindAll (condition));
但是,这会导致编译器错误,因为 !
无法应用于 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));
However, this results in a compiler error, as !
can't be applied to Predicate<SomeClass>
. Is there any way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 lambda 表达式就地定义匿名委托,该委托是否定谓词结果的结果:
另一种选择:
用法:
list.RemoveAll(!condition)
不起作用的原因是委托上没有定义!
运算符。这就是为什么您必须根据上面所示的条件
定义一个新委托。You could use a lambda expression to define an anonymous delegate inplace that is the result of negating the result of the predicate:
Another option:
Usage:
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 ofcondition
as shown above.这实际上是可能的,但可能与您习惯的形式略有不同。在 .NET 中,lambda 表达式可以解释为委托或解释为 表达式树。在表达式树上执行 NOT 操作相对简单。
以下是使用您的代码作为起点的示例:
This is actually possible, but maybe in a slightly different form than you're used to. In .NET, lambda expressions can either be interpreted as delegates OR as expression trees. It is relatively straightforward to perform a
NOT
operation on an expression tree.Here is a sample using your code as a starting point: