Return to Snippet

Revision: 10795
at January 13, 2009 19:04 by pckujawa


Initial Code
using System;
using System.Collections.Generic;

namespace testConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] stringArr = new string[] { "1", "2", "Text with spaces" };
            string text1;
            string text2;
            string text3;
            IEnumerator<string> stringEnum = Program.makeStringEnum(stringArr);
            stringEnum.MoveNext();
            text1 = stringEnum.Current; stringEnum.MoveNext();
            text2 = stringEnum.Current; stringEnum.MoveNext();
            text3 = stringEnum.Current; stringEnum.MoveNext();
        }

        static IEnumerator<string> makeStringEnum(string[] arr)
        {
            foreach (string str in arr)
            {
                yield return str;
            }
        }
    }
}

Initial URL
http://www.ondotnet.com/pub/a/dotnet/excerpt/progcsharp4_ch09-04/index.html

Initial Description
Ever need to enumerate over a collection of strings? Simple, just `foreach(string str in stringContainer)` and you've got them, right? Well, what if you want to enumerate over them manually? Basically, you can't (as far as I've found). You can do `stringContainer.GetEnumerator()`, but that returns a System.Collections.IEnumerator, which holds objects, not strings (thus requiring an explicit cast to get the string value). That is, you cannot do  
    `IEnumerator en = stringContainer.GetEnumerator();  
    en.MoveNext();  
    string myString = en.Current;`  
You have to do  
    `string myString = Convert.ToString(en.Current);`

I don't know why C# doesn't have this built in, but it doesn't (and trying to cast to IEnumerator&lt;string&gt; throws an exception). So, there are a lot of homegrown solutions out there, but this one is the easiest for my application. I needed to read in values from a file and assign them to string variables. Since there are a lot of variables, and their order is sometimes changed between versions, it is a pain to assign each variable by its array index (the array being created by reading in each line and splitting it with a comma). It is much easier to change the ordering of variables by simply moving the line up or down in the source code. Thus the need for an enumerator and my dilemma.

The URL refers to similar code from an O'Reilly book.

The 'yield return' statement essentially returns one value from a collection each time a value is needed (such as in a foreach or enum.MoveNext), but keeps track of ordering for you. Pretty slick. Google it for more info.

Initial Title
Create IEnumerable&lt;string&gt; to manually enumerate over string values

Initial Tags


Initial Language
C#