views:

49

answers:

2

Following is a T_SQL query for AdventureWorks database:

SELECT Name
FROM Production.Product
WHERE ListPrice >= ANY
(SELECT MAX (ListPrice)
FROM Production.Product
GROUP BY ProductSubcategoryID)

I try writing a LINQ query for this:

        var groupMaxPricesquery2 = from product in dc.Products
                                   group product by product.ProductSubcategoryID into productGroup
                                   select productGroup.Max(eachProductInGroup => eachProductInGroup.ListPrice);

        var query = from product in dc.Products
                    where groupMaxPricesquery2.Any(listPrice => listPrice <= product.ListPrice)
                    select product.Name;

How can I make it more beautiful (i.e. combining those queries together, or a more efficient approach)?

Thank you very much

A: 

Maybe I'm missing something with the grouping, but I don't see why it is necessary.

var maxListPrice = dc.Products.Max(p => p.ListPrice);
var query = dc.Products.Where(p => p.ListPrice >= maxListPrice).Select(n => n.Name);
Jay
Yes, I quite understand what you mean. Grouping isn't necessary here. I just use it because I want to make my LINQ query look like the T_SQL query.
It isn't necessary in the T-SQL query either -- it is just waste. You asked for a more beautiful and efficient approach; I think I provided both.
Jay
Yes, you're right. Your answer is beyond my expectation. My problem was that I just focused on the query syntax, not its meaning. Thank you very much for your help.
+1  A: 

Give either of these a try:

var query = from product in dc.Products
            let groupMaxPricesQuery = dc.Products.GroupBy(p => p.ProductSubcategoryID)
                                                 .Select(g => g.Max(item => item.ListPrice))
            where groupMaxPricesQuery.Any(listPrice => listPrice <= product.ListPrice)
            select product.Name;

// or
var query = dc.Products
              .Select(product => new {
                  Product = product,
                  GroupedMaxPrices = dc.Products.GroupBy(p => p.ProductSubcategoryID)
                                                .Select(g => g.Max(item => item.ListPrice))
            })
            .Where(item => item.GroupedMaxPrices.Any(listPrice => listPrice <= item.Product.ListPrice))
            .Select(item => item.Product.Name);
Ahmad Mageed
Thanks Ahmad. I've learned a lot from your answers. In the first query, it is the `let` clause that I need. The second query, you use the standard dot notation syntax. In this case, I find the first query more readable.
@Anonymous downvoter? Thanks for the unwarranted downvote...
Ahmad Mageed