Last active
April 30, 2022 20:41
-
-
Save icalvo/fd3f614d32a56a946375ad1759db7024 to your computer and use it in GitHub Desktop.
Merge sorted `IEnumerable` (also works if they are unbounded)
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 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