Search code examples
c#arraysenumerator

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

Solution

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

    IEnumerable<byte> udpDnsPacket = /*...*/;
    
    byte[] result = udpDnsPacket.ToArray();