Skip to content

IEnumerable possibly being enumerated more than once #491

@giggio

Description

@giggio

If an IEnumerable is being enumerated more than once you might have problems. Any calls to linq methods like Count() or Any() or Select() (or use in linq expressions) or calls to foreach should trigger this diagnostic on all lines that the enumeration is happening.

So this:

var myEnumerable = GetEnumerable();
var count = myEnumerable.Count();
var gtFive = from i in MyEnumerable
             select i;
foreach (var i in myEnumerable)
{}

Should trigger this diagnostic on lines 2, 3 and 5.

Fixes to:

var myEnumerable = GetEnumerable();
var myEnumerableList = myEnumberable.ToList();
var count = myEnumerableList.Count();
var gtFive = from i in myEnumerableList
             select i;
foreach (var i in myEnumerableList)
{}

Notes:

  • Messages should say "Might be enumerated more than once" because even though the type is an IEnumerable, it could be an IList at runtime.
  • ToList has to be available, so System.Linq has to be available. If is, but the using is not present at the .cs file, add it.

Diagnostic id: CC0100
Severity: Information
Category: Performance

Metadata

Metadata

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions