C# 使用 linq 获取最小值和最大值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16684769/
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
Get minimum and maximum value using linq
提问by Lakmal
I have a list that has values as displayed below
Using Linq how can i get the minimum from COL1 and maximum from COL2 for the selected id.
我有一个列表,其中的值如下所示
使用 Linq 如何从 COL1 获得最小值,从 COL2 获得所选 ID 的最大值。
id COL1 COL2
=====================
221 2 14
221 4 56
221 24 16
221 1 34
222 20 14
222 1 12
222 5 34
Based on the below list it should display id 221 1 56and 222 1 34help me out
根据下面的列表,它应该显示 id221 1 56并222 1 34帮助我
采纳答案by Habib
If you want Min and Max value for each ID in the list, then you have to group by IDand the get MAX and Min accordingly like:
如果您想要列表中每个 ID 的 Min 和 Max 值,那么您必须分组ID并相应地获取 MAX 和 Min,例如:
var query = yourList.GroupBy(r=> r.ID)
.Select (grp => new
{
ID = grp.Key,
Min = grp.Min(t=> t.Col1),
Max = grp.Max(t=> t.Col2)
});
Use Enumerable.Maxmethod to calculate maximum like:
使用Enumerable.Max方法计算最大值,如:
var max = yourList.Max(r=> r.Col1);
Use Enumerable.Minmethod to calculate minimum on a field like:
使用Enumerable.Min方法计算字段的最小值,例如:
var min = yourList.Min(r=> r.Col2);
回答by Gerard
You can sort, something like:
您可以排序,例如:
var min = yourList.OrderBy(p => p.Col1).First();
var max = yourList.OrderByDescending(p => p.Col1).First();

