C# langauge: Enumerators and iterators

in programming •  7 years ago 

CC.png

The enumerators and iterators in general are used to move after the elements of the collection, we will start by discussing the enumerations.

Enumerators

Enumerator class is used for calculations, it works similarly to foreach instructions, however, the enumerator can be said to be a more low-level version.

For example, a high-level type of iteration by the word “programmer” in foreach looks like this:

static void Main(string[] args)
{
     foreach (char c in "programmer")
        Console.WriteLine(c);
 
     Console.ReadKey();
}

And low-level looks like this:

static void Main(string[] args)
{
     using (var enumerator = "programmer".AsEnumerable().GetEnumerator())
         while (enumerator.MoveNext())
         {
             var element = enumerator.Current;
             Console.WriteLine(element);
 
         }
 
     Console.ReadKey();
}

First, we start to iterate from the first character or “p” as it is a “char” type so we must use the MoveNext() method in the while statement to be able to pass to the next characters if any exists.

Iterators

As the enumeration of subsequent elements of the collection is not very convenient and readable using the GetEnumerator() method, so something like iterators was created, thanks to them we do not need to use such methods as eg MoveNext() or GetEnumerator(), iterators use only yield return words used to return values from a loop. Below is a simple example:

static void Main(string[] args)
{
    foreach (char fib in Programmer("programmer"))
      Console.Write(fib + " ");
 
    Console.ReadKey();
}
 
static IEnumerable<char> Programmer(string couplechars)
{
     for (int i = 0; i < couplechars.Length; i++)
     {
         yield return couplechars[i];
     }
}

In order to be able to use the yield return statement, the method must be of the type IEnumerable in this method simply we throw in a string and return after one character to the foreach statement, i.e. char type.

However, what does the yield return statement means at all?

While the return word means “here is the value you asked for this method”, the yield return statement means “Here is the next item that you requested from this enumerator”.

yield break

As you might guess, the yield break statement is supposed to finish the iterator’s work prematurely. Example:

static void Main(string[] args)
{
     foreach (char fib in Programmer("programmer"))
        Console.Write(fib + " ");
 
     Console.ReadKey();
}
 
static IEnumerable<char> Programmer(string couplechars)
{
     for (int i = 0; i < couplechars.Length; i++)
     {
         if (i==5) yield break;
 
         yield return couplechars[i];
               
      }
}

I added only one instruction, when it will have the value 5, the method will stop returning subsequent values, as a result the program will return the string “p r o g r”.

Let’s now write our own method using the yield return statement which extracts the last three numbers from the table in which there are ten digits.

static void Main(string[] args)
{
    int[] table ={123, 435, 56, 2, 3, 5, 45, 56, 34, 43};
 
    foreach (var number in LastNumbers(table, 3))
    {
        Console.Write(" {0} ,", number);
    }
 
    Console.ReadKey();
}
 
static IEnumerable<int> LastNumbers(int[] number, int lastNumbers)
{
    for (int i = 0; i < number.Length; i++)
    {
        if (i >= number.Length - lastNumbers)
        {
            yield return number[i];
        }
    }
}

This content also you can find on my blog http://devman.pl/csharplan/c-langauge-enumerators-iterators/

If you recognise it as useful, share it with others so that others can also use it.

Leave upvote and follow and wait for next articles :) .

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!