Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible multiple enumeration of IEnumerable? [duplicate]

enter image description here

why is that ? how can I fix it ?

like image 670
Royi Namir Avatar asked Mar 03 '12 20:03

Royi Namir


People also ask

How do you fix multiple enumeration of IEnumerable?

If the underlying type of the IEnumerable collection is an iterator-based implementation generated by LINQ methods like Select or yield in C# or yield statement in Visual Basic, you can fix the violation by converting and caching the collection to another type.

What does possible multiple enumeration mean?

Deferred Danger. One of the many useful warnings in ReSharper is “Possible multiple enumeration of IEnumerable“. If you enumerate an enumerable more than once, ReSharper detects that and warns you about it. Although this warning may seem pointless at first, there are two good reasons to pay attention to it.

How do you fix multiple enumerations?

This kind of problem can be easily fixed — force the enumeration at the point of variable initialization by converting the sequence to an array or a list, for example: List<string> names = GetNames().

Why is multiple enumerations bad?

Enumerating an enumerable can be very expensive. For example, an enumerable might be backed by a database. Re-enumerating may force you to wait another network round trip. You don't want to pay that cost twice.


1 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.

like image 68
BrokenGlass Avatar answered Sep 21 '22 11:09

BrokenGlass