Skip to content

Instantly share code, notes, and snippets.

@bltavares
Created February 6, 2012 18:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bltavares/1754068 to your computer and use it in GitHub Desktop.
Save bltavares/1754068 to your computer and use it in GitHub Desktop.
RAnking functions extension methods - C# Enumerable
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