Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Zip all elements

Tags:

c#

linq

Is there a way utilize Enumerable.Zip, where all elements in both IEnumerables are used? If the IEnumerables 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"} ]
like image 256
budi Avatar asked Jan 05 '23 00:01

budi


2 Answers

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

like image 159
octavioccl Avatar answered Jan 13 '23 21:01

octavioccl


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.

like image 25
ejohnson Avatar answered Jan 13 '23 20:01

ejohnson