views:

3454

answers:

4

I was wondering if there are any times where it's advantageous to use an IEnumerator over a foreach loop for iterating through a collection? For example, is there any time where it would be better to use either of the following code samples over the other?

IEnumerator<MyClass> classesEnum = myClasses.GetEnumerator();
while(classesEnum.MoveNext())
    Console.WriteLine(classesEnum.Current);

instead of

foreach (var class in myClasses)
    Console.WriteLine(class);
+11  A: 

In C#, foreach is doing exactly the same thing as the IEnumerator code that you posted above. The foreach construct is provided to make it easier for the programmer. I believe that the IL generated in both cases is the same/similar.

Andy
+1 The IL is identical.
Andrew Hare
There are cases where you need to do it manually - see my answer below.
Marc Gravell
Actually, no the IL is **not** identical in his sample, because he hasn't checked the iterator for IDisposable. This is important for many iterators.
Marc Gravell
+2  A: 

According to the C# language spec:

A foreach statement of the form

foreach (V v in x) embedded-statement

is then expanded to:

{
    E e = ((C)(x)).GetEnumerator();
    try {
            V v;
            while (e.MoveNext()) {
                    v = (V)(T)e.Current;
                    embedded-statement
            }
    }
    finally {
            ... // Dispose e
    }
}

The essense of your two examples are the same, but there are some important differences, most notably the try/finally.

Jay Bazuzi
+1  A: 

I used it sometimes when the first iteration do something different from others.

For example, if you want to print members to console and separate results by line, you can write.

using (IEnumerator<MyClass> classesEnum = myClasses.GetEnumerator()) {
    if (classEnum.MoveNext())
        Console.WriteLine(classesEnum.Current);
    while (classesEnum.MoveNext()) {
        Console.WriteLine("-----------------");
        Console.WriteLine(classesEnum.Current);
    }
}

Then the result is

myClass 1
-----------------
myClass 2
-----------------
myClass 3

And another situation is when I iterate 2 enumerators together.

using (IEnumerator<MyClass> classesEnum = myClasses.GetEnumerator()) {
    using (IEnumerator<MyClass> classesEnum2 = myClasses2.GetEnumerator()) {
        while (classesEnum.MoveNext() && classEnum2.MoveNext())
            Console.WriteLine("{0}, {1}", classesEnum.Current, classesEnum2.Current);
    }
}

result

myClass 1, myClass A
myClass 2, myClass B
myClass 3, myClass C

Using enumerator allows you to do more flexible on your iteration. But in most case, you can use foreach

chaowman
+10  A: 

First, note that one big difference in your example (between foreach and GetEnumerator) is that foreach guarantees to call Dispose() on the iterator if the iterator is IDisposable. This is important for many iterators (which might be consuming an external data feed, for example).

Actually, there are cases where foreach isn't as helpful as we'd like.

First, there is the "first item" case discussed here (foreach / detecting first iteration).

But more; if you try writing the missing Zip method for stitching two enumerable sequences together (or the SequenceEqual method), you find that you can' use foreach on both sequences, since that would perform a cross-join. You need to use the iterator directly for one of them:

static IEnumerable<T> Zip<T>(this IEnumerable<T> left,
    IEnumerable<T> right)
{
    using (var iter = right.GetEnumerator())
    {
        // consume everything in the first sequence
        foreach (var item in left)
        {
            yield return item;

            // and add an item from the second sequnce each time (if we can)
            if (iter.MoveNext())
            {
                yield return iter.Current;
            }
        }
        // any remaining items in the second sequence
        while (iter.MoveNext())
        {
            yield return iter.Current;
        }                
    }            
}

static bool SequenceEqual<T>(this IEnumerable<T> left,
    IEnumerable<T> right)
{
    var comparer = EqualityComparer<T>.Default;

    using (var iter = right.GetEnumerator())
    {
        foreach (var item in left)
        {
            if (!iter.MoveNext()) return false; // first is longer
            if (!comparer.Equals(item, iter.Current))
                return false; // item different
        }
        if (iter.MoveNext()) return false; // second is longer
    }
    return true; // same length, all equal            
}
Marc Gravell
Shouldn't it be something like while(iter.MoveNext()) in case right has two or more elements than left?
Spoike
Zip? Yes... oops (fixed) - thanks kindly
Marc Gravell