user348173
user348173

Reputation: 9288

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

How do I convert List<byte[]> in one byte[] array, or one Stream?

Upvotes: 12

Views: 37710

Answers (5)

Ed Swangren
Ed Swangren

Reputation: 124790

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

Upvotes: 4

Dylan Beattie
Dylan Beattie

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

Twitch
Twitch

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

Peter Lillevold
Peter Lillevold

Reputation: 33950

SelectMany should do the trick:

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

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

Upvotes: 54

David Yaw
David Yaw

Reputation: 27894

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

Upvotes: 0

Related Questions