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/