16

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

1
  • Do you want min and max value for each ID ? Commented May 22, 2013 at 6:23

3 Answers 3

44

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);
Sign up to request clarification or add additional context in comments.

3 Comments

OP mentions for the selected id, so you should probably use Where to filter.
@VimalStan, yes, read the question again and modified the answer
Use }); instead of }: in the end of query.
4

You can sort, something like:

var min = yourList.OrderBy(p => p.Col1).First();
var max = yourList.OrderByDescending(p => p.Col1).First();

2 Comments

I think that sorting cost O(n x log(n)) and finding the max value only costs O(n). So sorting just for finding the min, max is not good answer.
Sorting performance is negligible when a query doesn't have to run every second. This answer is quite efficient over Habib's.
0

If you want to avoid making two calls to the database, there is another way to perform it:

var result = query.GroupBy(r => 0)
    .Select (grp => new 
    {
        Min = grp.Min(t => t.Col1), 
        Max = grp.Max(t => t.Col2)
    });

This will perform just one execution in the database, and it will return both results.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.