How can I say if the LINQ extension method suffers with double enumeration?

I am wondering what rules exist to determine if a portion of LINQ code suffers from double enumeration?

For example, what are the telltale signs that the following code might be a double enumeration? What are some other signs to look for?

public static bool MyIsIncreasingMonotonicallyBy<T, TResult>(this IEnumerable<T> list, Func<T, TResult> selector) where TResult : IComparable<TResult> { return list.Zip(list.Skip(1), (a, b) => selector(a).CompareTo(selector(b)) <= 0).All(b => b); } 
+6
source share
1 answer

Go to one of the following:

 public class OneTimeEnumerable<T> : IEnumerable<T> { public OneTimeEnumerable(IEnumerable<T> source) { _source = source; } private IEnumerable<T> _source; private bool _wasEnumerated = false; public IEnumerator<T> GetEnumerator() { if (_wasEnumerated) { throw new Exception("double enumeration occurred"); } _wasEnumerated = true; return _source.GetEnumerator(); } } 
+7
source

All Articles