获得使用LINQ最小值和最大值 [英] Get minimum and maximum value using linq

查看:1380
本文介绍了获得使用LINQ最小值和最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有作为显示如下结果
使用LINQ我怎样才能从COL1的最小和最大距离COL2所选的ID有值的列表。

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.

id     COL1      COL2
=====================
221     2         14
221     4         56   
221    24         16   
221     1         34
222    20         14    
222     1         12 
222     5         34    

根据下面的列表中就应该显示的识别码 221 1 56 222 1 34
帮我出

Based on the below list it should display id 221 1 56 and 222 1 34 help me out

推荐答案

如果您想要的最小值和最大值列表中的每个ID,然后通过 ID 并有组获得最大值和最小值相应的,如:

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:

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)
                              };

使用的Enumerable.Max 方法计算最大,如:

Use Enumerable.Max method to calculate maximum like:

var max = yourList.Max(r=> r.Col1);

使用的

Use Enumerable.Min method to calculate minimum on a field like:

var min = yourList.Min(r=> r.Col2);

这篇关于获得使用LINQ最小值和最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆