Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ get Max value from list

Tags:

linq

I have the following table:

 ID Amt  Received
 -- ---- --------
 2  55   N 
 2  88   Y
 2  44   N
 3  5    N
 3  9    N
 4  5    N
 5  33   Y
 6  43   N
 7  54   N

    var result = (from rs in db.Exp
                  where rs.ID == id
                  && rs.Received == true
                  select rs).Max().Any();

Given an ID, I need to find the max Amt for a given id and then check if it is Y, if so, return true else return false.

like image 552
Nate Pet Avatar asked Feb 22 '12 21:02

Nate Pet


2 Answers

This should do it;

db.Exp.
    Where(x => x.ID == id).
    OrderByDescending(x => x.Amt).
    Take(1).
    Any(x => x.Received == "Y");
like image 102
Joachim Isaksson Avatar answered Nov 02 '22 14:11

Joachim Isaksson


Unfortunately LINQ doesn't provide a "max by an attribute" method. MoreLINQ does with its MaxBy operator, but that can't be translated into SQL of course. So if this is a LINQ to SQL (or whatever) query, you'll need a different approach. If it's already LINQ to Objects, however:

return db.Exp.Where(rs => rs.ID == id)
             .MaxBy(rs => rs.Amt)
             .Received;

Note that this is doing what the words of your question ask:

  • Out of the records with the given ID...
  • Find the one with the highest amount...
  • And check the value of Received

This is not the same as:

  • Out of the records with the given ID where received is true...
  • Find the one with the highest amount

Also note that this will throw an exception if there are no records with that ID.

If you want to do it in LINQ to SQL etc, you'd probably be best off with an ordering:

var highest = db.Exp.Where(rs => rs.ID == id)
                    .OrderByDescending(rs => rs.Amt)
                    .FirstOrDefault();
return highest != null && highest.Received;

You don't want to do this if you're using LINQ to Objects, as it will order all the results, when you only want to find the result with the highest amount.

like image 36
Jon Skeet Avatar answered Nov 02 '22 13:11

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!