why is that ? how can I fix it ?
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.
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.
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().
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With