c# - 如何使用 Linq 获得最高值(value)

标签 c# linq

假设我有以下数据:

Name    Priority
A       3
A       5
B       1
C       1
C       3
C       2

我想获得具有最高优先级的不同名称列表,因此结果如下所示:

Name    Priority
A       5
B       1
C       3

我如何使用 Linq 来做到这一点?

最佳答案

var query = yourData
    .GroupBy(x => x.Name,
             (k, g) => g.Aggregate((a, x) => (x.Priority > a.Priority) ? x : a));

// and a quick test...
foreach (var result in query)
{
    Console.WriteLine(result.Name + " " + result.Priority);
}

关于c# - 如何使用 Linq 获得最高值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4873984/

相关文章:

c# - 调试时,有没有办法判断一个对象是否是不同的实例?

c# - Linq 到 SQL : Compare In-Memory Tuple List Array with Table

.net - LINQ Join 运算符是否使用嵌套循环、合并或 HashSet 连接?

c# - 如何在 Linq 连接期间设置 x.foo = y?

c# - 在建立关系后隐藏零个实体

c# - 将 List<Guid> 转换为 List<Guid? >

c# - 泛型与继承 : What am I doing wrong here?

c# - 指定的算法无效 - 自定义 STS

c# - 从服务器端 Blazor 应用程序调用 API 时,用户声明始终为空

c# - 何时在 Linq 中使用 Cast() 和 Oftype()