我想合并多个字节数组但是失败。最后一个数组只显示最后添加的字节数组,而不是所有字节数组。以下是我的尝试。
List<byte[]> d = new List<byte[]>();
foreach (var item in IDs)
{
obj = RequisitionsObj.GenerateLabOrderReq();
if (obj.Data != null)
{
d.Add(obj.Data);
}
}
byte[] final = Combine(d.SelectMany(a => a).ToArray());
private byte[] Combine(params byte[][] arrays)
{
byte[] rv = new byte[arrays.Sum(a => a.Length)];
int offset = 0;
foreach (byte[] array in arrays)
{
System.Buffer.BlockCopy(array, 0, rv, offset, array.Length);
offset += array.Length;
}
return rv;
}
答案 0 :(得分:5)
您不需要Combine
方法。只需使用SelectMany
:
List<byte[]> d = new List<byte[]>();
foreach (var item in IDs)
{
obj = RequisitionsObj.GenerateLabOrderReq();
if (obj.Data != null)
{
d.Add(obj.Data);
}
}
byte[] final = d.SelectMany(a => a).ToArray();
修改强>
工作样本:
List<byte[]> d = new List<byte[]>();
byte[] b1 = new byte[] { 1, 2, 3, 4 };
byte[] b2 = new byte[] { 5, 6, 7, 8 };
d.Add(b1);
d.Add(b2);
byte[] b3 = d.SelectMany(a => a).ToArray(); // Content is 1,2,3,4,5,6,7,8