Skip to content

Instantly share code, notes, and snippets.

@larsw
Last active November 18, 2016 18:18
Show Gist options
  • Save larsw/90dd08b0da2650841aa6c48464d855d7 to your computer and use it in GitHub Desktop.
Save larsw/90dd08b0da2650841aa6c48464d855d7 to your computer and use it in GitHub Desktop.
PartialOrderBy extension method over IEnumerable<T>
public static class EnumerableExtensions
{
public static IEnumerable<TSource> PartialOrderBy<TSource, TKey>(this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
IComparer<TKey> comparer)
{
var list = new List<TSource>(source);
while (list.Count > 0)
{
var minimum = default(TSource);
var minimumKey = default(TKey);
foreach (TSource s in list)
{
TKey k = keySelector(s);
minimum = s;
minimumKey = k;
break;
}
foreach (TSource s in list)
{
TKey k = keySelector(s);
if (comparer.Compare(k, minimumKey) < 0)
{
minimum = s;
minimumKey = k;
}
}
yield return minimum;
list.Remove(minimum);
}
yield break;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment