Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

c# - 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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...