Question

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();
Was it helpful?

Solution

Assuming you have an IEnumerable<T>, you can use the Enumerable.ToArray extension method:

IEnumerable<byte> udpDnsPacket = /*...*/;

byte[] result = udpDnsPacket.ToArray();

OTHER TIPS

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.

Since you have an IEnumerator<byte> and not an IEnumerable<byte>, you cannot use Linq's ToArray method. ToArray is an extension method on IEnumerable<T>, not on IEnumerator<T>.

I'd suggest writing an extension method similar to Enumerable.ToArray but then for the purpose of creating an array of your enumerator:

public T[] ToArray<T>(this IEnumerator<T> source)
{
    T[] array = null;
    int length = 0;
    T t;
    while (source.MoveNext())
    {
        t = source.Current();
        if (array == null)
        {
            array = new T[4];
        }
        else if (array.Length == length)
        {
            T[] destinationArray = new T[length * 2];
            Array.Copy(array, 0, destinationArray, 0, length);
            array = destinationArray;
        }
        array[length] = t;
        length++;
    }
    if (array.Length == length)
    {
        return array;
    }
    T[] destinationArray = new T[length];
    Array.Copy(array, 0, destinationArray, 0, length);
    return destinationArray;
}

What happens is that you iterate your enumerator item by item and add them to an array that is gradually increasing in size.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top