Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't IEnumerable<T> have FindAll or RemoveAll methods?

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?

like image 662
Andy Avatar asked Mar 19 '12 14:03

Andy


3 Answers

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;
like image 192
Marc Gravell Avatar answered Nov 05 '22 22:11

Marc Gravell


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.

like image 39
Anders Forsgren Avatar answered Nov 05 '22 23:11

Anders Forsgren


For RemoveAll isn't applicable on IEnumerable because IEnumerable is read-only. For FindAll, see Marc's answer.

like image 1
Arnaud F. Avatar answered Nov 05 '22 22:11

Arnaud F.