mic*_*ael 3 c# linq arrays performance concatenation
如果我有一个字符串数组,例如:var array = new[] { "the", "cat", "in", "the", "hat" },我想加入它们,每个单词之间有一个空格我可以简单地调用String.Join(" ", array).
但是,假设我有一个整数数组数组(就像我可以有一个字符数组数组).我想将它们组合成一个大型数组(展平它们),但同时在每个数组之间插入一个值.
var arrays = new[] { new[] { 1, 2, 3 }, new[] { 4, 5, 6 }, new { 7, 8, 9 }};
var result = SomeJoin(0, arrays); // result = { 1, 2, 3, 0, 4, 5, 6, 0, 7, 8, 9 }
Run Code Online (Sandbox Code Playgroud)
我写了一些东西,但它非常难看,我确信有更好,更清洁的方式.也许效率更高?
var result = new int[arrays.Sum(a => a.Length) + arrays.Length - 1];
int offset = 0;
foreach (var array in arrays)
{
Buffer.BlockCopy(array, 0, result, offset, b.Length);
offset += array.Length;
if (offset < result.Length)
{
result[offset++] = 0;
}
}
Run Code Online (Sandbox Code Playgroud)
也许这是最有效的?我不知道......只是看看是否有更好的方法.我想也许LINQ可以解决这个问题,但遗憾的是我没有看到任何我需要的东西.
您可以通过以下方式一般"加入"序列:
public static IEnumerable<T> Join<T>(T separator, IEnumerable<IEnumerable<T>> items)
{
var sep = new[] {item};
var first = items.FirstOrDefault();
if (first == null)
return Enumerable.Empty<T>();
else
return first.Concat(items.Skip(1).SelectMany(i => sep.Concat(i)));
}
Run Code Online (Sandbox Code Playgroud)
这适用于您的代码:
var arrays = new[] { new[] { 1, 2, 3 }, new[] { 4, 5, 6 }, new { 7, 8, 9 }};
var result = Join(0, arrays); // result = { 1, 2, 3, 0, 4, 5, 6, 0, 7, 8, 9 }
Run Code Online (Sandbox Code Playgroud)
这里的优点是,这将适用于任何IEnumerable<IEnumerable<T>>,并不限于列表或数组.请注意,这将在两个空序列之间插入一个单独的,但如果需要,可以修改该行为.