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 = anObject.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.
Assuming you have an IEnumerable<T>, you can use the Enumerable.ToArray extension method:
IEnumerable<byte> udpDnsPacket = /*...*/;
byte[] result = udpDnsPacket.ToArray();
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.
精彩评论