Why do we need iterators in c#?

前端 未结 10 1896
情话喂你
情话喂你 2021-02-05 18:35

Can somebody provide a real life example regarding use of iterators. I tried searching google but was not satisfied with the answers.

相关标签:
10条回答
  • 2021-02-05 19:19

    The canonical and simplest example is that it makes infinite sequences possible without the complexity of having to write the class to do that yourself:

    // generate every prime number
    public IEnumerator<int> GetPrimeEnumerator()
    {
        yield return 2;
        var primes = new List<int>();
        primesSoFar.Add(2);
        Func<int, bool> IsPrime = n => primes.TakeWhile(
            p => p <= (int)Math.Sqrt(n)).FirstOrDefault(p => n % p == 0) == 0;
    
        for (int i = 3; true; i += 2)
        {
            if (IsPrime(i))
            {
                yield return i;
                primes.Add(i);
            }
        }
    }
    

    Obviously this would not be truly infinite unless you used a BigInt instead of int but it gives you the idea. Writing this code (or similar) for each generated sequence would be tedious and error prone. the iterators do that for you. If the above example seems too complex for you consider:

    // generate every power of a number from start^0 to start^n
    public IEnumerator<int> GetPowersEnumerator(int start)
    {   
        yield return 1; // anything ^0 is 1
        var x = start;
        while(true)
        {
            yield return x;
            x *= start;
        }      
    }
    

    They come at a cost though. Their lazy behaviour means you cannot spot common errors (null parameters and the like) until the generator is first consumed rather than created without writing wrapping functions to check first. The current implementation is also incredibly bad(1) if used recursively.

    Wiriting enumerations over complex structures like trees and object graphs is much easier to write as the state maintenance is largely done for you, you must simply write code to visit each item and not worry about getting back to it.


    1. I don't use this word lightly - a O(n) iteration can become O(N^2)
    0 讨论(0)
  • 2021-02-05 19:29

    Beside everything else, to iterate through lazy-type sequences - IEnumerators. Each next element of such sequence may be evaluated/initialized upon iteration step which makes it possible to iterate through infinite sequences using finite amount of resources...

    0 讨论(0)
  • 2021-02-05 19:34

    Iterate through the students in a class

    The Iterator design pattern provides us with a common method of enumerating a list of items or array, while hiding the details of the list's implementation. This provides a cleaner use of the array object and hides unneccessary information from the client, ultimately leading to better code-reuse, enhanced maintainability, and fewer bugs. The iterator pattern can enumerate the list of items regardless of their actual storage type.

    0 讨论(0)
  • 2021-02-05 19:34

    Iterate through a set of homework questions.

    But seriously, Iterators can provide a unified way to traverse the items in a collection regardless of the underlying data structure.

    Read the first two paragraphs here for a little more info.

    0 讨论(0)
提交回复
热议问题