[ACCEPTED]-Convert List<byte[]> to one byte[] array-.net

Accepted answer
Score: 53

SelectMany should do the trick:

var listOfArrays = new List<byte[]>();

byte[] array = listOfArrays
                .SelectMany(a => a)
                .ToArray();

0

Score: 7
var myList = new List<byte>();
var myArray = myList.ToArray();

EDIT: OK, turns out the question was actually 3 about List<byte[]> - in which case you need to use SelectMany 2 to flatten a sequence of sequences into 1 a single sequence.

var listOfArrays = new List<byte[]>();
var flattenedList = listOfArrays.SelectMany(bytes => bytes);
var byteArray = flattenedList.ToArray();

Docs at http://msdn.microsoft.com/en-us/library/system.linq.enumerable.selectmany.aspx

Score: 4

You can use List<T>.ToArray().

0

Score: 3

This is probably a little sloppy, could 2 use some optimizing, but you get the gist 1 of it

var buffers = new List<byte[]>();    
int totalLength = buffers.Sum<byte[]>( buffer => buffer.Length );    
byte[] fullBuffer = new byte[totalLength];

int insertPosition = 0;
foreach( byte[] buffer in buffers )
{
    buffer.CopyTo( fullBuffer, insertPosition );
    insertPosition += buffer.Length;
}
Score: 0

If you're using the actual class System.Collections.Generic.List<byte>, call 1 ToArray(). It returns a new byte[].

More Related questions