views:

205

answers:

3

I am dropping this line after having visited different websites to try understand real time example of using custom enumeration.I got examples.But they lead me to confusion.

Example

Take 1

class NumberArray
{
    public int[] scores;

    public NumberArray()
    {
    }

    public NumberArray(int[] scores)
    {
        this.scores = scores;
    }

    public int[] Scores
    {
        get {return scores;}
    }

}

Take 2

public class Enumerator : IEnumerator
{
    int[] scores;
    int cur;
    public Enumerator(int[] scores)
    {
        this.scores = scores;
        cur = -1;
    }
    public Object Current
    {
          get {
               return scores[cur];
             }
    }

    public void Reset()
    {
        cur = -1;
    }

    public bool MoveNext()
    {
            cur++;
            if (cur < scores.Length)
                return true;
            else return false;
    }
}

public class Enumerable : IEnumerable
{
    int[] numbers;

    public void GetNumbersForEnumeration(int[] values)
    {
        numbers = values;
        for (int i = 0; i < values.Length; i++)
            numbers[i] = values[i];
    }

    public IEnumerator GetEnumerator()
    {
        return new Enumerator(numbers);
    }
}

Main

static void Main()
        {
            int[] arr = new int[] { 1, 2, 3, 4, 5 };
            NumberArray num = new NumberArray(arr);
            foreach(int val in num.Scores)
            {
                Console.WriteLine(val);
            }

            Enumerable en = new Enumerable();
            en.GetNumbersForEnumeration(arr);

            foreach (int i in en)
            {
                Console.WriteLine(i);
            }
            Console.ReadKey(true);
        }

In take 2 ,I folowed the custom iteration to iterate the same integer array as i did in take 2.Why should i beat about the bush to iterate an integer by using custom iteration?

Probably i missed out the real-time custom iteration need.Can you explain me the task which i can't do with exisiting iteration facility.(Just I finished my schooling,so give me a simple example ,so that i can understand it properly).

Update : Those examples i took from some site.As nothing special in that code ,moreover we can achieve it very simply even without using custom iteration,my interest was to know the real scenario where cutom iteration is quite handy.

+5  A: 

Custom iterators are useful when the resources you are iterating are not pre-loaded in memory, but rather obtained as needed in each iteration. For example, in LINQ to SQL, when you do something like:

foreach(var employee in dataContext.Employees) {
    // Process employee
}

in each step of the foreach loop, the Employees table in the database is queried to get the next record. This way, if you exit the loop early, you haven't read the whole table, but only the records you needed.

See here for a real-world example: enumerate lines on a file. Here, each line is read from the file on each iteration of the foreach loop. (as a side note, .NET Framework 4 offers this same functionality built-in).

Konamiman
And it is useful as a state machine check these links: http://blogs.msdn.com/matt_pietrek/archive/2004/07/26/197242.aspx and http://bigballofmud.wordpress.com/2009/03/21/creating-simple-state-machines-using-c-20-iterators/
Audrius
linq to sql doesn't *actually* run a select N+1 when you iterate (it loads all records when you request the first result) but it's a good example. +1
Rob Fonseca-Ensor
+2  A: 

To be honest, I am not entirely sure what you're asking, but if you're concerned about the difference between returning an array (as in take 1) and returning an iterator (take 2), here is my answer.

There a big difference between returning an array and returning an iterator. Returning an array means returning internal state (unless you make a copy as part of the return, but that is expensive). If you return an iterator, you just return an abstraction, that will let callers iterate state. This also means, that you can do lazy evaluation if you need to (something you obviously can't do if you're returning an array).

Also, with the support for iterators in C# 2, there is really no reason to implement IEnumerable by hand. Please see this question for additional detail http://stackoverflow.com/questions/1330489/can-someone-demystify-the-yield-keyword/1330543#1330543

Brian Rasmussen
Those examples i took from some site.So i did n't understand the benefit of custom iteration. I wanted to konw the scenario "this is where custom iteration is quite handy".
+2  A: 

Just as another example where custom iteration has been useful to me in the past was to provide a common abstraction to recursively enumerate all nodes in a tree structure...

foreach (Node n in tree)
  //...do something
flq