Skip to content

Instantly share code, notes, and snippets.

@nelsonprsousa
Created May 30, 2023 18:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nelsonprsousa/5ec8114d58d77eeba5c8855fb3860403 to your computer and use it in GitHub Desktop.
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.
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