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();
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.