Convert list <byte []> to one byte [] array

How to convert List<byte[]> into one byte[] array or one Stream ?

+6
c #
source share
5 answers

SelectMany should do the trick:

 var listOfArrays = new List<byte[]>(); byte[] array = listOfArrays .SelectMany(a => a) .ToArray(); 
+36
source share
 var myList = new List<byte>(); var myArray = myList.ToArray(); 

EDIT: OK, it turns out that the question was actually about List<byte[]> - in this case you need to use SelectMany to smooth the sequence of sequences into one 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

+7
source share

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

+4
source share

This is probably a bit sloppy, may use some optimization, but you get its gist

 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; } 
+1
source share

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

0
source share

All Articles