How do I convert List<byte[]> in one byte[] array, or one Stream?
5 Answers
SelectMany should do the trick:
var listOfArrays = new List<byte[]>();
byte[] array = listOfArrays
.SelectMany(a => a)
.ToArray();
1 Comment
RichK
+1 for being the only one to notice the OP has a List<byte[]> rather than List<byte>
var myList = new List<byte>();
var myArray = myList.ToArray();
EDIT: OK, turns out the question was actually about List<byte[]> - in which case you need to use SelectMany to flatten a sequence of sequences into 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
2 Comments
Brad Christie
(reference) List<T>.ToArray()
Peter Lillevold
The OP have fixed her/his question, we're talking about
List<byte[]>.You can use List<T>.ToArray().
1 Comment
Peter Lillevold
No, but perhaps because the OP have fixed her/his question. We're talking about
List<byte[]>.This is probably a little sloppy, could use some optimizing, but you get the gist 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;
}
1 Comment
youen
This is probably more efficient than Peter Lillevold answer (though I haven't tested)