Is there a way utilize Enumerable.Zip, where all elements in both IEnumerable
s are used? If the IEnumerable
s have different counts, default remaining merges to default(T)
.
Examples
var first = new int[] { 1, 2, 3, 4, 5 };
var second = new string[] { "a", "b", "c" };
var zipped = first.Zip(second, (f, s) => new { f, s });
// actual: [ {1, "a"}, {2, "b"}, {3, "c"} ]
// expecting: [ {1, "a"}, {2, "b"}, {3, "c"}, {4, null}, {5, null} ]
var first = new int[] { 1, 2, 3 };
var second = new string[] { "a", "b", "c", "d", "e" };
var zipped = first.Zip(second, (f, s) => new { f, s });
// actual: [ {1, "a"}, {2, "b"}, {3, "c"} ]
// expecting: [ {1, "a"}, {2, "b"}, {3, "c"}, {0, "d"}, {0, "e"} ]
Well you can create your custom Zip
extension method:
static IEnumerable<T> Zip<T1, T2, T>(this IEnumerable<T1> first,
IEnumerable<T2> second, Func<T1, T2, T> operation)
{
using (var iter1 = first.GetEnumerator())
using (var iter2 = second.GetEnumerator())
{
while (iter1.MoveNext())
{
if (iter2.MoveNext())
{
yield return operation(iter1.Current, iter2.Current);
}
else
{
yield return operation(iter1.Current, default(T2));
}
}
while (iter2.MoveNext())
{
yield return operation(default(T1), iter2.Current);
}
}
}
The main idea was taken from this post answer. You can test it in dotnetfiddle if you want
Try MoreLinq's ZipLongest method:
If the two input sequences are of different lengths then the result sequence will always be as long as the longer of the two input sequences. The default value of the shorter sequence element type is used for padding. This operator uses deferred execution and streams its results.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With