Skip to content

Instantly share code, notes, and snippets.

@tormodfj
Created July 28, 2010 09:19
Show Gist options
  • Save tormodfj/493845 to your computer and use it in GitHub Desktop.
Save tormodfj/493845 to your computer and use it in GitHub Desktop.
Creates a sorted merge between an arbitrary amount of sorted sequences.
public static IEnumerable<T> SortMerge<T, TKey>(Func<T, TKey> orderBy, params IEnumerable<T>[] sortedEnumerables)
{
var enumerators = sortedEnumerables
.Select(e => e.GetEnumerator())
.Where(e => e.MoveNext())
.ToList();
while (enumerators.Any())
{
var next = enumerators
.OrderBy(e => orderBy(e.Current))
.First();
var indexOfNext = enumerators.IndexOf(next);
yield return enumerators[indexOfNext].Current;
if (!enumerators[indexOfNext].MoveNext())
{
enumerators.RemoveAt(indexOfNext);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment