Possible multiple enumeration of IEnumerable? [dup

2019-03-13 01:07发布

问题:

This question already has an answer here:

  • Handling warning for possible multiple enumeration of IEnumerable 7 answers

why is that ? how can I fix it ?

回答1:

There is nothing to fix here. Any() will iterate the enumeration but stop after the first element (after which it returns true).

Multiple enumerations are mainly a problem in two cases:

  • Performance: Generally you want to avoid multiple iterations if you can, because it is slower. This does not apply here since Any() will just confirm there is at least one element and is a required check for you. Also you are not accessing any remote/external resources, just an in-memory sequence.

  • Enumerations that cannot be iterated over more than once: E.g. receiving items from a network etc. - also does not apply here.

As a non Linq version that only needs to iterate once you could do the following:

bool foundAny= false;
bool isEqual = true;

if(f == null)
  throw new ArgumentException();

foreach(var check in f)
{
   foundAny = true;
   isEqual = isEqual && check(p,p2);
}

if(!foundAny)
  throw new ArgumentException();

return isEqual;

But, as noted, in your case it does not make a difference, and I would go with the version that is more readable to you.



回答2:

The Any method can cause the enumeration of the IEnumerable<T>, if it doesn't have another way to determine the result. In some cases it can be a problem, for instance if the IEnumerable<T> instance is actually an IQueryable<T> that will cause a database query or web service call to be executed. Now, if it's just an in-memory collection, it's not really an issue, because enumerating the collection won't have noticeable side effects. And anyway, Any will use the Count property if the sequence implements ICollection<T>, so it won't cause an enumeration.