Possible multiple enumerations of IEnumerable collection
Possible multiple enumerations of IEnumerable collection
Microsoft docsDescription
A collection of type IEnumerable or IEnumerable\<T\> has the ability to defer enumeration when it's generated. Many LINQ methods, such as Select, use deferred execution. Enumeration starts when the collection is passed into a LINQ enumeration method, like ElementAt, or used in a for each statement. The enumeration result is not calculated once and cached, like Lazy.
If the enumeration operation itself is expensive, for example, a query into a database, multiple enumerations would hurt the performance of the program.
If the enumeration operation has side effects, multiple enumerations might result in bugs.
Cause
Detected multiple enumerations of an IEnumerable collection.
How to fix violations
If the underlying type of your IEnumerable collection is some other type, such as List or Array, it's safe to convert the collection to its underlying type to fix the diagnostic.
Violation:
Fix:
If the underlying type of the IEnumerable collection uses an iterator-based implementation (for example, if it's generated by LINQ methods like System.Linq.Enumerable.Select or by using the yield keyword), you can fix the violation by materializing the collection. However, this allocates extra memory.
For example:
Violation:
Fix:
Example
public void MyMethod(IEnumerable<int> input)
{
var count = input.Count();
foreach (var i in input) { }
}When to suppress
It's safe to suppress this warning if the underlying type of the IEnumerable collection is some other type like List or Array, or if you're sure that methods that take an IEnumerable collection don't enumerate it.