Skip to content

Instantly share code, notes, and snippets.

@icalvo
Last active April 30, 2022 20:41
Show Gist options
  • Save icalvo/fd3f614d32a56a946375ad1759db7024 to your computer and use it in GitHub Desktop.
Save icalvo/fd3f614d32a56a946375ad1759db7024 to your computer and use it in GitHub Desktop.
Merge sorted `IEnumerable` (also works if they are unbounded)
public static IEnumerable<T> Merge<T, TKey>(this IEnumerable<IEnumerable<T>> lists, Func<T, TKey> selector) where TKey : IComparable<TKey>
{
var enumerators = lists.Select(x => x.GetEnumerator()).ToList();
try
{
enumerators.RemoveAll(x => !x.MoveNext());
while (enumerators.Any())
{
var minEnumerator = enumerators.MinBy(x => selector(x.Current))!;
yield return minEnumerator.Current;
Debug.Assert(minEnumerator != null, nameof(minEnumerator) + " != null");
if (!minEnumerator.MoveNext())
{
enumerators.Remove(minEnumerator);
}
}
}
finally
{
foreach (var enumerator in enumerators)
{
enumerator.Dispose();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment