Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select multiple values after using Max() in LINQ to Objects?

I have the following LINQ query:

var query =
    (from p in obj1
     group p by p.objID into g
     let totalSum = g.Sum(p => p.ObjPrice)
     select new { MyObjectID = g.Key, totalSum })
    .Max(g => g.totalSum);

I want to select both the object id and price of the object with the maximum price. How can I do that?

like image 261
SeeSharp Avatar asked Nov 16 '25 06:11

SeeSharp


1 Answers

Use an order by descending clause and call FirstOrDefault().

(from p in obj1
group p by p.objID into g
let totalSum = g.Sum(p => p.ObjPrice)
orderby totalSum descending
select new { MyObjectID = g.Key, totalSum }).FirstOrDefault();
like image 150
Daniel A. White Avatar answered Nov 18 '25 20:11

Daniel A. White



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!