NO ... in foreach, "GetEnumerator" is called only once (ever), and this will be used in the future.
EDIT: here I am making an expression that the result set is temporarily stored ... this is only true for some cases ... not for this, so I took it.
EDIT: Please forgive this for being too verbose ... but I wanted to show you what is happening ... so here is the console application :)
using System; using System.Collections.Generic; using System.Linq; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { foreach (string item in MyCustomEnumerator() .Where(item => item.StartsWith("abc"))) { Console.WriteLine(item); } } static IEnumerable<string> MyCustomEnumerator() { Console.WriteLine(DateTime.Now); yield return "abc1"; Console.WriteLine(DateTime.Now); yield return "abc2"; Console.WriteLine(DateTime.Now); yield return "abc3"; Console.WriteLine(DateTime.Now); yield return "xxx"; } } }
EDIT: this will result in using DateTime, then abc1, then DateTime, then abc2, then DateTime, then abc3, then DateTime.
Timothy Khouri
source share