Last active
August 29, 2015 13:56
-
-
Save yar-shukan/9140858 to your computer and use it in GitHub Desktop.
TakeFromGrouped
This file contains 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
using System; | |
using System.Collections.Generic; | |
namespace TakeFromGroup | |
{ | |
public static class EnumerableExtensions | |
{ | |
public static IEnumerable<T> TakeFromGrouped<T, TGroup>(this IEnumerable<T> enumerable, | |
Func<T, TGroup> groupSelector, | |
Func<T, T, T> takeFunc) | |
{ | |
var taken = new Dictionary<TGroup, T>(); | |
foreach (T value in enumerable) | |
{ | |
T currentTaken; | |
TGroup groupKey = groupSelector(value); | |
if (taken.TryGetValue(groupKey, out currentTaken)) | |
{ | |
currentTaken = takeFunc(value, currentTaken); | |
} | |
else | |
{ | |
currentTaken = value; | |
} | |
taken[groupKey] = currentTaken; | |
} | |
return taken.Values; | |
} | |
public static IEnumerable<T> TakeMinFromGrouped<T, TGroup, TKey>(this IEnumerable<T> enumerable, | |
Func<T, TGroup> groupSelector, | |
Func<T, TKey> keySelector, | |
IComparer<TKey> comparer = null) | |
{ | |
SetDefaultIfNull(ref comparer); | |
return enumerable.TakeFromGrouped(groupSelector, | |
(x, y) => comparer.Compare(keySelector(x), keySelector(y)) < 0 ? x : y); | |
} | |
public static IEnumerable<T> TakeMaxFromGrouped<T, TGroup, TKey>(this IEnumerable<T> enumerable, | |
Func<T, TGroup> groupSelector, | |
Func<T, TKey> keySelector, | |
IComparer<TKey> comparer = null) | |
{ | |
SetDefaultIfNull(ref comparer); | |
return enumerable | |
.TakeFromGrouped(groupSelector, | |
(x, y) => comparer.Compare(keySelector(x), keySelector(y)) > 0 ? x : y); | |
} | |
private static void SetDefaultIfNull<T>(ref IComparer<T> comparer) | |
{ | |
if (comparer == null) | |
{ | |
comparer = Comparer<T>.Default; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment