LINQ get maximum value from list

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 the identifier, I need to find max Amt for the given identifier, and then check if it is Y, if so, return true else return false.

+6
source share
4 answers

That should do it;

 db.Exp. Where(x => x.ID == id). OrderByDescending(x => x.Amt). Take(1). Any(x => x.Received == "Y"); 
+18
source

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.

+6
source

You need to say that you want Max .

 var result = (from rs in db.Exp where rs.ID == id && rs.Received select rs) .Max(row => row.Amt) == Y; 

And you don't need .Any()

+3
source
 // "I need to find the max Amt for a given id..." var elementWithMaxAmount = db.Exp .Where(x => x.ID == id) .OrderByDescending(x => x.Amount) .FirstOrDefault(); // "... and then check if it is Y" var result = (elementWithMaxAmount != null && elementWithMaxAmount.Received == "Y"); 
0
source

Source: https://habr.com/ru/post/909130/


All Articles