Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get minimum and maximum value using linq

Tags:

c#

asp.net

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    

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

like image 351
Lakmal Avatar asked May 22 '13 06:05

Lakmal


2 Answers

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

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);
like image 134
Habib Avatar answered Sep 28 '22 19:09

Habib


You can sort, something like:

var min = yourList.OrderBy(p => p.Col1).First();
var max = yourList.OrderByDescending(p => p.Col1).First();
like image 21
Gerard Avatar answered Sep 28 '22 19:09

Gerard