Created
July 28, 2010 09:19
-
-
Save tormodfj/493845 to your computer and use it in GitHub Desktop.
Creates a sorted merge between an arbitrary amount of sorted sequences.
This file contains hidden or 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> 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