I always thought that these two methods were similar:
public static IEnumerable<Func<int>> GetFunctions()
{
for(int i = 1; i <= 10; i++)
yield return new Func<int>(() => i);
}
public static IEnumerable<Func<int>> GetFunctionsLinq()
{
return Enumerable.Range(1, 10).Select(i => new Func<int>(() => i));
}
Yet, they yield different results when converting them to a List<Func<int>>
:
List<Func<int>> yieldList = GetFunctions().ToList();
List<Func<int>> linqList = GetFunctionsLinq().ToList();
foreach(var func in yieldList)
Console.WriteLine("[YIELD] {0}", func());
Console.WriteLine("==================");
foreach(var func in linqList)
Console.WriteLine("[LINQ] {0}", func());
The output is:
[YIELD] 11
[YIELD] 11
[YIELD] 11
[YIELD] 11
[YIELD] 11
[YIELD] 11
[YIELD] 11
[YIELD] 11
[YIELD] 11
[YIELD] 11
==================
[LINQ] 1
[LINQ] 2
[LINQ] 3
[LINQ] 4
[LINQ] 5
[LINQ] 6
[LINQ] 7
[LINQ] 8
[LINQ] 9
[LINQ] 10
Why is this?