Unfortunately, LINQ does not provide a "max by a attribute" method. MoreLINQ works with its MaxBy
, but this, of course, cannot be translated into SQL. Therefore, if it is a LINQ to SQL query (or any other), you will need a different approach. If it is already LINQ for objects:
return db.Exp.Where(rs => rs.ID == id) .MaxBy(rs => rs.Amt) .Received;
Note that this does what the words of your question ask about:
- From records with this ID ...
- Find the one with the highest amount ...
- And check the
Received
value
This is not the same as:
- From records with this identifier, where it is received true ...
- Find the highest amount
Also note that this will throw an exception if there are no records with this identifier.
If you want to do this in LINQ to SQL, etc., you will probably be best placed to place an order:
var highest = db.Exp.Where(rs => rs.ID == id) .OrderByDescending(rs => rs.Amt) .FirstOrDefault(); return highest != null && highest.Received;
You do not want to do this if you use LINQ to Objects, since it will order all the results when you want to find the result with the largest sum.
source share