Why use the yield keyword, when I could just use an ordinary IEnumerable?

前端 未结 8 1256
渐次进展
渐次进展 2020-12-22 15:08

Given this code:

IEnumerable FilteredList()
{
    foreach( object item in FullList )
    {
        if( IsItemInPartialList( item ) )
                 


        
      
      
      
8条回答
  •  误落风尘
    2020-12-22 15:44

    You can use yield to return items that aren't in a list. Here's a little sample that could iterate infinitely through a list until canceled.

    public IEnumerable GetNextNumber()
    {
        while (true)
        {
            for (int i = 0; i < 10; i++)
            {
                yield return i;
            }
        }
    }
    
    public bool Canceled { get; set; }
    
    public void StartCounting()
    {
        foreach (var number in GetNextNumber())
        {
            if (this.Canceled) break;
            Console.WriteLine(number);
        }
    }
    

    This writes

    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    0
    1
    2
    3
    4
    

    ...etc. to the console until canceled.

提交回复
热议问题