Created
February 6, 2012 18:57
-
-
Save bltavares/1754068 to your computer and use it in GitHub Desktop.
RAnking functions extension methods - C# Enumerable
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 class EnumerableExt { | |
public static IEnumerable<U> Rank<T, TKey, U>( | |
this IEnumerable<T> source, | |
Func<T, TKey> keySelector, | |
Func<T, int, U> selector) | |
{ | |
if (!source.Any()) | |
{ | |
yield break; | |
} | |
T[] ordered = source.OrderBy(keySelector).ToArray(); | |
TKey previous = keySelector(ordered[0]); | |
int rank = 1; | |
foreach (T t in ordered) | |
{ | |
TKey current = keySelector(t); | |
if (!current.Equals(previous)) | |
{ | |
rank++; | |
} | |
yield return selector(t, rank); | |
previous = current; | |
} | |
} | |
public static IEnumerable<U> DescendingRank<T, TKey, U>( | |
this IEnumerable<T> source, | |
Func<T, TKey> keySelector, | |
Func<T, int, U> selector) | |
{ | |
if (!source.Any()) | |
{ | |
yield break; | |
} | |
T[] ordered = source.OrderByDescending(keySelector).ToArray(); | |
TKey previous = keySelector(ordered[0]); | |
int rank = 1; | |
foreach (T t in ordered) | |
{ | |
TKey current = keySelector(t); | |
if (!current.Equals(previous)) | |
{ | |
rank++; | |
} | |
yield return selector(t, rank); | |
previous = current; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment