why is that ? how can I fix it ?
-
1All but the final screenshot and text just distract from the real question. – usr Mar 03 '12 at 20:19
-
1This is very similar to http://stackoverflow.com/q/7244178/219583 . Any() will count as one enumeration and Aggregate() as the 2nd. – Bruno Silva Mar 03 '12 at 20:20
-
12Don't post code as screenshots -- paste the source into the question. – Joe Mar 03 '12 at 20:25
-
1This message has been brought up on StackOverflow before - the following two questions may clarify what's going on for you: http://stackoverflow.com/questions/8240844/handling-warning-for-possible-multiple-enumeration-of-ienumerable http://stackoverflow.com/questions/6593825/resharper-possible-multiple-enumeration-of-ienumerable – kaj Mar 03 '12 at 20:30
2 Answers
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.

- 158,293
- 28
- 286
- 335
-
2
-
1@usr: Agreed, I added that to the first case - it does make a difference in this case whether it's a remote/external resource or an in-memory sequence – BrokenGlass Mar 03 '12 at 20:30
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.

- 286,951
- 70
- 623
- 758