I found myself in a situation where I had to do some stuff with elements of a list and then remove them from that list :
foreach (var element in someList.Where(e => e.IsMatching))
{
// do some stuff
}
someList.RemoveAll(e => e.IsMatching);
This woks perfectly but I don't like the duplicate lambda, so I declared a Func<T, bool> x = e => e.IsMatching;
and then tried to use x
as a parameter for .Where
and .RemoveAll
but I wasn't able to use x
for .RemoveAll
because its overload only accepts Predicate<T>
.
Why isn't an implicit nor explicit cast possible since both have the same return and parameter types?
(I am not looking for a way to make the conversion, everything about it is already in this quesion )
It is a little silly that the IEnumerable<T>.Where
extension method and List<T>
's RemoveAll
method take two different types. However, this is a simple work-around, since the local function can be used to initialize both a Func<int, bool>
and a Predicate<int>
:
var l = new List<int> {1, 2, 3, 5, 5, 6, 6};
bool Pred(int i) => i < 5;
var wh = l.Where(Pred);
var rem = l.RemoveAll(Pred);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.