How Yield works within a ForEach block?

How Yield works within a foreach loop shown below? lstNumbers is of type List<int> .

foreach (int i in lstNumbers)
{
    yield return i;
}

Will it start returning as it receives the value or it returns the final list at the end?

How is it different from:

   foreach (int i in lstNumbers)
    {
        return i;
    }

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.


In first case it just returns i in the moment of call to return i .

After the caller calls an iterator over the function again it will jump to the next iteration.

Example to make it clear:

int GetNextNumber() {
  foreach (int in in lstNumbers)
  {
     yield return in;  //returns on first hit
  }
}

and after

foreach(var i in GetNextNumber()) {
     //process number got from the GetNextNumber()
     //on next iteration GetNextNumber() will be called again 
     // so the next number from lstNumbers will be returned
}

It's a very common way to dealing with long data streams, where you sequentially pick on piece of it process and after request another, and so on..

In second case, instead, you will just always return the first element in the list, and never jump to others.

链接地址: http://www.djcxy.com/p/54316.html

上一篇: 从IEnumerable转换到IEnumerator

下一篇: 产量如何在ForEach块内工作?