[英]Need help for a more beautiful LINQ to SQL query
Following is a T_SQL query for AdventureWorks database: 以下是AdventureWorks数据库的T_SQL查询:
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: 我尝试为此编写一个LINQ查询:
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 (ie combining those queries together, or a more efficient approach)? 我怎样才能使其更美观(即将那些查询组合在一起,或更有效的方法)?
Thank you very much 非常感谢你
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);
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.