12

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

5 Answers 5

54

SelectMany should do the trick:

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

byte[] array = listOfArrays
                .SelectMany(a => a)
                .ToArray();
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for being the only one to notice the OP has a List<byte[]> rather than List<byte>
7
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

(reference) List<T>.ToArray()
The OP have fixed her/his question, we're talking about List<byte[]>.
4

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

1 Comment

No, but perhaps because the OP have fixed her/his question. We're talking about List<byte[]>.
3

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

This is probably more efficient than Peter Lillevold answer (though I haven't tested)
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.