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

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

Given this code:

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


        
      
      
      
8条回答
  •  离开以前
    2020-12-22 15:41

    The best real world example I've seen for the use of yield would be to calculate a Fibonacci sequence.

    Consider the following code:

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(string.Join(", ", Fibonacci().Take(10)));
            Console.WriteLine(string.Join(", ", Fibonacci().Skip(15).Take(1)));
            Console.WriteLine(string.Join(", ", Fibonacci().Skip(10).Take(5)));
            Console.WriteLine(string.Join(", ", Fibonacci().Skip(100).Take(1)));
            Console.ReadKey();
        }
    
        private static IEnumerable Fibonacci()
        {
            long a = 0;
            long b = 1;
    
            while (true)
            {
                long temp = a;
                a = b;
    
                yield return a;
    
                b = temp + b;
            }
        }
    }
    

    This will return:

    1, 1, 2, 3, 5, 8, 13, 21, 34, 55
    987
    89, 144, 233, 377, 610
    1298777728820984005
    

    This is nice because it allows you to calculate out an infinite series quickly and easily, giving you the ability to use the Linq extensions and query only what you need.

提交回复
热议问题