简体   繁体   English

转换列表 <byte[]> 到一个字节[]数组

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

如何在一个byte[]数组或一个Stream转换List<byte[]>

SelectMany should do the trick: SelectMany应该做的诀窍:

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

byte[] array = listOfArrays
                .SelectMany(a => a)
                .ToArray();
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. 编辑:好的,事实证明问题实际上是关于List<byte[]> - 在这种情况下,您需要使用SelectMany将序列序列展平为单个序列。

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 文档来自http://msdn.microsoft.com/en-us/library/system.linq.enumerable.selectmany.aspx

您可以使用List <T> .ToArray()

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;
}

If you're using the actual class System.Collections.Generic.List<byte> , call ToArray(). 如果您使用的是实际的类System.Collections.Generic.List<byte> ,请调用ToArray()。 It returns a new byte[] . 它返回一个新的byte[]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM