C# - How to create an array from an enumerator

Greg picture Greg · Aug 21, 2010 · Viewed 21.4k times · Source

In C#, what's the most elegant way to create an array of objects, from an enumerator of objects? e.g. in this case I have an enumerator that can return byte's, so I want to convert this to byte[].

EDIT: Code that creates the enumerator:

IEnumerator<byte> enumerator = updDnsPacket.GetEnumerator();

Answer

Brian Genisio picture Brian Genisio · Aug 21, 2010

OK, So, assuming that you have an actual enumerator (IEnumerator<byte>), you can use a while loop:

var list = new List<byte>();
while(enumerator.MoveNext())
  list.Add(enumerator.Current);
var array = list.ToArray();

In reality, I'd prefer to turn the IEnumerator<T> to an IEnumerable<T>:

public static class EnumeratorExtensions
{
    public static IEnumerable<T> ToEnumerable<T>(this IEnumerator<T> enumerator)
    {
      while(enumerator.MoveNext())
          yield return enumerator.Current;
    }
}

Then, you can get the array:

var array = enumerator.ToEnumerable().ToArray();

Of course, all this assumes you are using .Net 3.5 or greater.