It seems to me that a lot of the extension methods on IList<T>
are just as applicable to IEnumerable<T>
- such as FindAll
and RemoveAll
.
Can anyone explain the reasoning why they are not there?
It seems to me that a lot of the extension methods on IList<T>
are just as applicable to IEnumerable<T>
- such as FindAll
and RemoveAll
.
Can anyone explain the reasoning why they are not there?
RemoveAll
makes no sense since there is no Remove
etc on that API - however there is a FindAll
from 3.5 onwards - but it is known as Where
:
IEnumerable<Foo> source = ...
var filtered = source.Where(x => x.IsActive && x.Id = 25);
which is equivalent to:
IEnumerable<Foo> source = ...
var filtered = from x in source
where x.IsActive && x.Id == 25
select x;
Enumerable does not imply there is an underlying collection, so you can't know whether there is something to remove from or not. If there is an underlying collection, you don't know whether it supports a remove operation.
Here is an example method that enumerates odd numbers. If you could "remove" 7 from enumerable, what would happen? Where would it be removed from?
public IEnumerable<int> GetOddPositiveNumbers()
{
int i = 0;
while (true)
{
yield return 2*(i++)+1;
}
}
What you might be looking for is Where
and Except
that allows you to filter the enumerable.
To be fair something like IEnumerable<T>.RemoveAll
can actually make sense if what you actually want is a zero length version of a particular collection. Calling it RemoveAll
does NOT make sense since no IEnumerable<T>
method implementation should modify a collection.
So in my case I sometimes use a custom extension method I call Nil
.
static IEnumerable<T> Nil<T>(this IEnumerable<T> self) {
yield break;
}
As for FindAll
as Marc already pointed out is simply called Where
.
For RemoveAll
isn't applicable on IEnumerable
because IEnumerable is read-only.
For FindAll
, see Marc's answer.
All IEnumerable
does is specify that there is a collection that can be enumerated or iterated over. It does not even specify that the collection can be iterated over multiple times, let alone manipulated. Therefore, any methods that manipulate the collection do not make sense. Methods such as FindAll
would make sense, however.