BlackVegetable BlackVegetable - 9 months ago 40
C# Question

Simple IEnumerator use (with example)

I am having trouble remembering how (but not why) to use

s in C#. I am used to Java with its wonderful documentation that explains everything to beginners quite nicely. So please, bear with me.

I have tried learning from other answers on these boards to no avail. Rather than ask a generic question that has already been asked before, I have a specific example that would clarify things for me.

Suppose I have a method that needs to be passed an
object. All the method needs to do is concatenate the letters
to the end of every
in the iterator. It then will return this new iterator (of course the original
object is left as it was).

How would I go about this? The answer here should help many with basic questions about these objects in addition to me, of course.

Answer Source

Here is the documentation on IEnumerator. They are used to get the values of lists, where the length is not necessarily known ahead of time (even though it could be). The word comes from enumerate, which means "to count off or name one by one".

IEnumerator and IEnumerator<T> provided by all IEnumerable and IEnumerable<T> (the latter providing both) in .NET via GetEnumerator(). This is important because the foreach statement is designed to work directly with enumerators through those interface methods.

So for example:

IEnumerator enumerator = enumerable.GetEnumerator();

while (enumerator.MoveNext())
    object item = enumerator.Current;
    // Perform logic on the item


foreach(object item in enumerable)
    // Perform logic on the item

As to your specific scenario, almost all collections in .NET implement IEnumerable. Because of that, you can do the following:

public IEnumerator Enumerate(IEnumerable enumerable)
    // List implements IEnumerable, but could be any collection.
    List<string> list = new List<string>(); 

    foreach(string value in enumerable)
        list.Add(value + "roxxors");
    return list.GetEnumerator();