MaxBy()有办法获取多个最大值吗?

3

我正在尝试从列表中获取最大值,但如果有多个最大值,则要获取所有最大值。

例如,我有: Name1,31 Name2,35 Name3,33 Name4,35

我想要得到: {Name2,35}和{Name4,35}

我尝试使用MaxBy();

但那只返回第一个项目(Name2,35) 非常感谢您的帮助

struct Amounts
{
    public string Name;
    public int Total;
}

Amount highestAmount = amounts.MaxBy(x => x.Total);

Amount highestAmount = amounts.MaxBy(x => x.Total);


2
amounts.GroupBy(x => x.Total).MaxBy(g => g.Key) - Alexander Petrov
2个回答

3

您可以先使用GroupBy,然后在每个键上使用MaxBy来完成此操作。以下是一个扩展方法

public static IEnumerable<TSource> MaxsBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource,TKey> keySelector)
{
    return source.GroupBy(keySelector).MaxBy(g => g.Key);
}

这里是一个可工作的演示

using System;
using System.Linq;
using System.Collections.Generic;

public class Program
{
    struct Amounts
    {
        public string Name;
        public int Total;
    }

    public static void Main()
    {
        var amounts = new List<Amounts>
        {
            new Amounts { Name = "Name1", Total = 31 },
            new Amounts { Name = "Name2", Total = 35 },
            new Amounts { Name = "Name3", Total = 32 },
            new Amounts { Name = "Name4", Total = 35 }
        };
        var results = amounts.MaxsBy(x => x.Total);
        Console.WriteLine(string.Join("\n", results.Select(x => x.Name)));
    }
}

public static class Extensions 
{
    public static IEnumerable<TSource> MaxsBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource,TKey> keySelector)
    {
        return source.GroupBy(keySelector).MaxBy(g => g.Key);
    }
}

输出

Name2
Name4

1
另一种方法是当您无法确定 GroupBy 的键时(例如,如果您的 Comparer 考虑多个属性),可以使用。
    List<T> MultipleMax<T>(IList<T> list, IComparer<T> comparer)
    {
        var max = list.Max(comparer);
        if (max == null)
        {
            return new List<T>();
        }

        return list.Where(t => comparer.Compare(max, t) == 0).ToList();
    }

对(有创意),但通常当你想要一个最大值时,它会是最大的数字 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接