Not all sequences are repeatable, so they usually need to be counted. To help it, you can call ToList() in a sequence - even if typed as IEnumerable<T> , LINQ-to-Objects will still shrink and use .Count - so very cheap and repeatable.
For an example of a non-repeatable sequence:
static int evil; static IEnumerable<int> GetSequence() { foreach(var item in Enumerable.Range(1, Interlocked.Increment(ref evil))) yield return item; }
with demo:
var sequence = GetSequence(); Console.WriteLine(sequence.Count()); // 1 Console.WriteLine(sequence.Count()); // 2 Console.WriteLine(sequence.Count()); // 3
source share