【问题标题】:Merge multiple byte arrays c#合并多个字节数组c#
【发布时间】:2017-07-27 07:01:27
【问题描述】:

我想合并多个字节数组但失败了。最终数组只显示最后添加的字节数组,而不是所有字节数组。以下是我的尝试。

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

【问题讨论】:

    标签: c# arrays array-merge


    【解决方案1】:

    您不需要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
    

    【讨论】:

    • 我刚刚用一个样本试了一下(见我的编辑),它按预期工作。您的代码中一定有其他事情发生
    猜你喜欢
    • 2016-11-15
    • 1970-01-01
    • 1970-01-01
    • 2022-06-17
    • 1970-01-01
    • 2021-03-20
    • 2017-01-11
    • 2010-09-29
    • 1970-01-01
    相关资源
    最近更新 更多