Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - How to create an array from an enumerator

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();
like image 556
Greg Avatar asked Aug 21 '10 12:08

Greg


1 Answers

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.

like image 166
Brian Genisio Avatar answered Nov 15 '22 20:11

Brian Genisio