申请& quot;加入"的最佳方法是什么?方法通常类似于String.Join(...)的工作方式? [英] What's the best way to apply a "Join" method generically similar to how String.Join(...) works?
问题描述
如果我有一个字符串数组,例如:var array = new[] { "the", "cat", "in", "the", "hat" }
,并且我想将它们连接在一起,并且每个单词之间都有一个空格,那么我可以简单地调用String.Join(" ", array)
.
If I have a string array, for example: var array = new[] { "the", "cat", "in", "the", "hat" }
, and I want to join them with a space between each word I can simply call String.Join(" ", array)
.
但是,说我有一个整数数组的数组(就像我可以有一个字符数组的数组一样).我想将它们组合成一个大数组(展平它们),但同时在每个数组之间插入一个值.
But, say I had an array of integer arrays (just like I can have an array of character arrays). I want to combine them into one large array (flatten them), but at the same time insert a value between each 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 }
我写了一些东西,但是很丑陋,我敢肯定有更好,更干净的方法.也许更有效率?
I wrote something up, but it is very ugly, and I'm sure that there is a better, cleaner way. Maybe more efficient?
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;
}
}
也许这是最有效的?我不知道...只是看看是否有更好的方法.我以为LINQ可能会解决这个问题,但可惜我没有看到我需要的任何东西.
Perhaps this is the most efficient? I don't know... just seeing if there is a better way. I thought maybe LINQ would solve this, but sadly I don't see anything that is what I need.
推荐答案
您可以通过以下方式一般地加入"序列:
You can generically "join" sequences via:
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)));
}
这适用于您的代码:
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 }
此处的优点是,它将与任何IEnumerable<IEnumerable<T>>
一起使用,并且不仅限于列表或数组.请注意,这将在两个空序列之间插入一个分隔符,但是如果需要,可以修改该行为.
The advantage here is that this will work with any IEnumerable<IEnumerable<T>>
, and isn't restricted to lists or arrays. Note that this will insert a separate in between two empty sequences, but that behavior could be modified if desired.
这篇关于申请& quot;加入"的最佳方法是什么?方法通常类似于String.Join(...)的工作方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!