Reputation: 9288
How do I convert List<byte[]>
in one byte[]
array, or one Stream
?
Upvotes: 12
Views: 37710
Reputation: 54160
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
Upvotes: 7
Reputation: 46
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;
}
Upvotes: 3
Reputation: 33950
SelectMany
should do the trick:
var listOfArrays = new List<byte[]>();
byte[] array = listOfArrays
.SelectMany(a => a)
.ToArray();
Upvotes: 54
Reputation: 27894
If you're using the actual class System.Collections.Generic.List<byte>
, call ToArray(). It returns a new byte[]
.
Upvotes: 0