What are the benefits of a Deferred Execution in LINQ?

后端 未结 3 600
误落风尘
误落风尘 2020-11-22 14:04

LINQ uses a Deferred Execution model which means that resulting sequence is not returned at the time the Linq operators are called, but instead these operators return an obj

3条回答
  •  旧巷少年郎
    2020-11-22 14:50

    Another benefit of deferred execution is that it allows you to work with infinite series. For instance:

    public static IEnumerable FibonacciNumbers()
    {
        yield return 0;
        yield return 1;
    
        ulong previous = 0, current = 1;
        while (true)
        {
            ulong next = checked(previous + current);
            yield return next;
            previous = current;
            current = next;
    
        }
    }
    

    (Source: http://chrisfulstow.com/fibonacci-numbers-iterator-with-csharp-yield-statements/)

    You can then do the following:

    var firstTenOddFibNumbers = FibonacciNumbers().Where(n=>n%2 == 1).Take(10);
    foreach (var num in firstTenOddFibNumbers)
    {
        Console.WriteLine(num);
    }
    

    Prints:

    1
    1
    3
    5
    13
    21
    55
    89
    233
    377

    Without deferred execution, you would get an OverflowException or if the operation wasn't checked it would run infinitely because it wraps around (and if you called ToList on it would cause an OutOfMemoryException eventually)

提交回复
热议问题