使用Zip()合并不同长度的数组而不会丢失值 [英] Merge different length arrays without losing a value using Zip()
问题描述
在下面的代码中,我将合并两个类型为int
和string
的数组.第一个长度大于第二个长度,因此,最后一个索引(5
)不会合并:
In the following code, I'm merging two arrays of types int
and string
. The first one's length is bigger than the second one, and as a result, the last index (which is 5
) doesn't get merged:
int[] numbers = new[] { 1, 2, 3, 4, 5 };
string[] words = new string[] { "one", "two", "three", "four" };
var numbersAndWords = numbers.Zip(words, (n, w) => new { Number = n, Word = w });
foreach (var nw in numbersAndWords)
{
Console.WriteLine(nw.Number + nw.Word);
}
我想知道一种将其合并的方法.例如,在words
中存在的最后一个字符串之后创建一个null
或空字符串,并使用它与最后一个numbers
索引合并.无法弄清楚.
I would like to know a way of getting it merged. For example, creating a null
or empty string after the last one that exists in words
and using it to merge with the last numbers
index. Couldn't figure it out.
修改: 结果我得到
1one
2two
3three
4four
我想要的结果
1one
2two
3three
4four
5
谢谢!
不是重复项,我的另一个问题是关于在空对象上调用方法.
Not a duplicate, my other question is about calling method on a null object.
推荐答案
您可以轻松编写自己的类似LINQ的扩展方法来实现:
You can easily write your own LINQ-like extension method that will do it:
public static class MyEnumerable
{
public static IEnumerable<TResult> ZipWithDefault<TFirst, TSecond, TResult>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TSecond, TResult> selector)
{
bool firstMoveNext, secondMoveNext;
using (var enum1 = first.GetEnumerator())
using (var enum2 = second.GetEnumerator())
{
while ((firstMoveNext = enum1.MoveNext()) & (secondMoveNext = enum2.MoveNext()))
yield return selector(enum1.Current, enum2.Current);
if (firstMoveNext && !secondMoveNext)
{
yield return selector(enum1.Current, default(TSecond));
while (enum1.MoveNext())
{
yield return selector(enum1.Current, default(TSecond));
}
}
else if (!firstMoveNext && secondMoveNext)
{
yield return selector(default(TFirst), enum2.Current);
while (enum2.MoveNext())
{
yield return selector(default(TFirst), enum2.Current);
}
}
}
}
}
但是,如果您的源始终是一对数组,则简单地使用for
循环可能会更容易:
But if your source is always a pair of arrays, it might be easier to simply use for
loop:
public static IEnumerable<TResult> ZipWithDefault<TFirst, TSecond, TResult>(this TFirst[] first, TSecond[] second, Func<TFirst, TSecond, TResult> selector)
{
var maxLength = Math.Max(first.Length, second.Length);
for(var i = 0; i < maxLength; i++)
{
var firstItem = i < first.Length ? first[i] : default(TFirst);
var secondItem = i < second.Length ? second[i] : default(TSecond);
yield return selector(firstItem, secondItem);
}
}
这篇关于使用Zip()合并不同长度的数组而不会丢失值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!