I have a product table, for example:
ProductID ProductName Price 1 Milk 10 2 Banana 20 3 Apple 15 1 Grapes 12 2 Banana 25 1 Milk 8
I want to find products that have a maximum price for each product.
Sampling Result: -
ProductID ProductName Price 1 Grapes 12 2 Banana 25 3 Apple 15
I tried this query: -
List<Product> groups = products .GroupBy(p => p.ProductId) .Select(p => new Product { ProductId = p.Key, Name = p.OrderByDescending(o => o.Price).First().Name, Price = p.OrderByDescending(o => o.Price).First().Price, }) .ToList();
This query works fine, but my question is: should I use OrderByDescending
twice? I mean, since I just need a separate element based on 1 property, and suppose there are several other properties, so I need to use the same logic over and over again?
Edit: Sorry, I forgot to mention, please assume that ProductName may be different, check the updated tables.
source share