c# - 将 IEnumerable<byte[]> 转换为 byte[]

标签 c# linq

 var  r = from s in tempResult    
          select Encoding.GetEncoding("iso-8859-1").GetBytes(s);

我明白了,这会返回 IEnumerable<byte[]> ,但我正在寻找 LINQ 方法来转换整个 IEnumerable<byte[]>byte[] .

最佳答案

到目前为止提供的答案都不起作用,因为它们会转换 IEnumerable<byte[]>byte[][] .如果您的目标是获取可枚举中的所有数组并生成一个大数组,请尝试以下操作:

byte[] result = r.SelectMany(i => i).ToArray();

参见 this ideone example .


请注意,这不是最有效的方法。将原始查询结果转换为列表,然后计算数组长度之和会更快。完成后,您可以立即分配最终数组,然后再遍历结果列表并将每个结果数组的内容复制到更大的数组中。

上面的 LINQ 查询确实使这项任务变得容易,但速度不会很快。如果此代码成为应用程序中的瓶颈,请考虑以这种方式重写它。


我不妨提供一个更有效的实现示例:

public static T[] JoinArrays<T>(this IEnumerable<T[]> self)
{
    if (self == null)
        throw new ArgumentNullException("self");

    int count = 0;

    foreach (var arr in self)
        if (arr != null)
            count += arr.Length;

    var joined = new T[count];

    int index = 0;

    foreach (var arr in self)
        if (arr != null)
        {
            Array.Copy(arr, 0, joined, index, arr.Length);
            index += arr.Length;
        }

    return joined;
}

请注意,您传入的任何可枚举项都将被枚举两次,因此如果查询开销很大,最好传入列表或数组而不是查询。

关于c# - 将 IEnumerable<byte[]> 转换为 byte[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7044358/

相关文章:

c# - 使用 Ninject 内核作为工作单元对象工厂

c# - 是否有更简洁的 linq 方法来 'Union' 单个项目?

c# - EF6 : Use reference/lookup data with IQueryable

c# - await 在异步操作后不恢复上下文?

c# - 使用 select 和 bool 数组过滤字符串数组

c# - 如何使用控制面板程序功能中显示的复选框

c# - Linq 包括集合中的子项

jquery - 为什么没有 "compound method call statement",即 ".="?

c# - 从字符串列名称动态创建 LINQ Select 表达式

c# - GridView RowDataBound 不会在回发时触发