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?
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 ofconditionas shown above.