C# 如何使用linq查找具有最大值的项目?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15265588/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:10:35  来源:igfitidea点击:

How to find item with max value using linq?

c#linqmax

提问by user1784622

Have a look at the below table:

看看下表:

Item          Value
A                10
b                50
c                90

I want to find the item with maximum value. I can get that by using group byor orderding, but somehow I have a feeling there should be a more direct way. Am I right?

我想用maximum value. 我可以通过使用group byor来获得它orderding,但不知何故我觉得应该有一种更直接的方法。我对吗?

回答by Sergey Berezovskiy

With EF or LINQ to SQL:

使用 EF 或 LINQ to SQL:

var item = db.Items.OrderByDescending(i => i.Value).FirstOrDefault();

With LINQ to Objects I suggest to use morelinqextension MaxBy(get morelinq from nuget):

对于 LINQ to Objects,我建议使用morelinq扩展MaxBy(从 nuget 获取 morelinq):

var item = items.MaxBy(i => i.Value);