In this example it will return all the values, one by one, but the consuming code needs to start iterating over the resultset:
foreach (int i in lstNumbers)
{
yield return i;
}
Take a look at the following example which will print 1, 2
on the console and the for
loop inside the method will never reach an end if the consuming code doesn't iterate over the enumerable:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
foreach (var item in Get().Take(2))
{
Console.WriteLine(item);
}
}
static IEnumerable<int> Get()
{
foreach (var item in new[] { 1, 2, 3 })
{
yield return item;
}
}
}
You probably don't need to be yielding anything in this case but simply return the result because you already have it:
return lstNumbers;
whereas in the second case:
foreach (int i in lstNumbers)
{
return i;
}
you are simply returning the first value of the list and the iteration breaks immediately.