为什么IEnumerable <T>没有FindAll或RemoveAll方法?

And*_*ndy 13 c# linq collections ienumerable extension-methods

在我看来,很多扩展方法IList<T>都适用于IEnumerable<T>- 例如FindAllRemoveAll.

谁能解释为什么他们不存在的原因?

Mar*_*ell 21

RemoveAll是没有意义的,因为没有Remove对API等等-但有一个FindAll从3.5开始-但它被称为Where:

IEnumerable<Foo> source = ...
var filtered = source.Where(x => x.IsActive && x.Id = 25);
Run Code Online (Sandbox Code Playgroud)

这相当于:

IEnumerable<Foo> source = ...
var filtered = from x in source
               where x.IsActive && x.Id == 25
               select x;
Run Code Online (Sandbox Code Playgroud)


And*_*ren 9

可枚举并不意味着存在底层集合,因此您无法知道是否存在要删除的内容.如果一个底层集合,你不知道它是否支持删除操作.

这是一个枚举奇数的示例方法.如果你可以从可枚举中"删除"7,会发生什么?从哪里删除?

public IEnumerable<int> GetOddPositiveNumbers()
{
   int i = 0;
   while (true)
   {          
      yield return 2*(i++)+1;
   }
}
Run Code Online (Sandbox Code Playgroud)

你可能会寻找是WhereExcept它允许您筛选的枚举.