1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| public static IEnumerable<TSource> AllMaxBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector)
{
return source.AllMaxBy(selector, null);
}
public static IEnumerable<TSource> AllMaxBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector, IComparer<TKey> comparer)
{
comparer = comparer ?? Comparer<TKey>.Default;
TKey maxValue = default(TKey);
List<TSource> max = new List<TSource>();
bool first = true;
foreach (var item in source)
{
TKey value = selector(item);
int compare = comparer.Compare(value, maxValue);
if (compare > 0 || first)
{
maxValue = value;
max.Clear();
max.Add(item);
}
else if (compare == 0)
{
max.Add(item);
}
first = false;
}
return max.ToArray();
} |