使用linq获取最小值和最大值

时间:2023-02-04 16:05:55

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帮助我

1 个解决方案

#1


32  

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的最小值和最大值,则必须按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);

#1


32  

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的最小值和最大值,则必须按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);