Should I use OrderByDescending twice in LINQ?

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.

+6
source share
2 answers

No, you do not need, you can just select First() :

 new Product { ProductId = p.Key, Name = p.First().Name, Bar = p.First().Bar, Price = p.OrderByDescending(o => o.Price).First().Price, } 

This, of course, assumes that all products with a given ProductId have the same Name and Bar .

If this is not the case, and you want to display all the properties from the selected object, create a code block in Select() :

 .Select(p => { var havingHighestPrice = p.OrderByDescending(o => o.Price).First() return new Product { ProductId = p.Key, Name = havingHighestPrice.Name, Bar = havingHighestPrice.Bar, Price = havingHighestPrice.Price, } }) 
+5
source

Linq query syntax can be used to store local variables:

 var groups = from p in products.GroupBy(x => x.ProductId) let first = p.OrderByDescending(o => o.Price).First() select new Product { ProductId = p.Key, Name = first.Name, Price = first.Price, }; 

The important thing is that it is safe to use in Entity Framework queries.

+1
source

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


All Articles