Created
May 30, 2023 18:59
-
-
Save nelsonprsousa/5ec8114d58d77eeba5c8855fb3860403 to your computer and use it in GitHub Desktop.
ZipLongest returns a projection of tuples, where each tuple contains the N-th element from each of the argument sequences. The resulting sequence will always be as long as the longest of input sequences.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class EnumerableExtensions | |
{ | |
public static IEnumerable<TResult> ZipLongest<TResult>(this IEnumerable<TResult> first, IEnumerable<TResult> second) | |
{ | |
if (first == null) | |
{ | |
throw new ArgumentNullException(nameof(first)); | |
} | |
if (second == null) | |
{ | |
throw new ArgumentNullException(nameof(second)); | |
} | |
using var iter1 = first.GetEnumerator(); | |
using var iter2 = second.GetEnumerator(); | |
while (iter1.MoveNext()) | |
{ | |
yield return iter1.Current; | |
if (iter2.MoveNext()) | |
{ | |
yield return iter2.Current; | |
} | |
} | |
while (iter2.MoveNext()) | |
{ | |
yield return iter2.Current; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment