[英]Get minimum and maximum value using linq
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 56
and 222 1 34
help me out根据下面的列表,它应该显示 id 221 1 56
和222 1 34
帮我解决
If you want Min and Max value for each ID in the list, then you have to group by ID
and 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.Max method to calculate maximum like:使用Enumerable.Max方法计算最大值,如:
var max = yourList.Max(r=> r.Col1);
Use Enumerable.Min method to calculate minimum on a field like:使用Enumerable.Min方法计算字段的最小值,例如:
var min = yourList.Min(r=> r.Col2);
You can sort, something like:您可以排序,例如:
var min = yourList.OrderBy(p => p.Col1).First();
var max = yourList.OrderByDescending(p => p.Col1).First();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.