It will be repeated 6 times. Once for Where and once for an element for Max .
Code demonstrating this:
private static int count = 0; public static IEnumerable<int> Regurgitate(IEnumerable<int> source) { count++; Console.WriteLine("Iterated sequence {0} times", count); foreach (int i in source) yield return i; } int[] Numbers = new int[5] { 5, 2, 3, 4, 5 }; IEnumerable<int> sequence = Regurgitate(Numbers); var query = from a in sequence where a == sequence.Max(n => n) select a;
He will print "Iterated Sequence 6 Times."
We could make a more universal shell, more flexible if you plan to use it to experiment with other cases:
public class EnumerableWrapper<T> : IEnumerable<T> { private IEnumerable<T> source; public EnumerableWrapper(IEnumerable<T> source) { this.source = source; } public int IterationsStarted { get; private set; } public int NumMoveNexts { get; private set; } public int IterationsFinished { get; private set; } public IEnumerator<T> GetEnumerator() { IterationsStarted++; foreach (T item in source) { NumMoveNexts++; yield return item; } IterationsFinished++; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public override string ToString() { return string.Format( @"Iterations Started: {0} Iterations Finished: {1} Number of move next calls: {2}" , IterationsStarted, IterationsFinished, NumMoveNexts); } }
This has several advantages over another function:
- It records both the number of iterations started, the number of completed iterations, and the total number of times that all sequences have been increased.
- You can create different instances to transfer different base sequences, which allows you to check multiple sequences for each program, and not just one when a static variable is used.
Servy
source share