【发布时间】:2020-02-02 19:55:27
【问题描述】:
我想为以下场景构建一个 Linq 查询:
表 1
PriceId
ProductId
ProductPrice
ProductHeight
ProductWeight
ProductType
表 2
ProductId
ProductName
任务: 为以下产品选择最便宜的价格和名称:
- productHeight = 5
- productWeight = 10
- 产品类型:“abc”、“xyz”
最终的预期结果是这样的对象列表:
ProductId
ProductName
TheCheapestPrice(the cheapest ProductPrice)
我创建了一个 SQL 查询来获取此信息,但是我遇到了问题 用 LINQ 编写它。
SQL 查询:
SELECT
t1.ProductId,
t2.ProductName,
MIN(t1.ProductPrice) AS TheCheapestPrice
FROM
Table1 t1
INNER JOIN Table2 t2 ON t1.ProductId = t2.ProductId
WHERE
t1.ProductHeight = 5
AND
t1.ProductWeight = 10
AND
t1.ProductType IN ('abc', 'xyz')
GROUP BY
t1.ProductId,
t2.ProductName
你能帮我在 LINQ 中实现同样的结果吗?
到目前为止,我创建了这样一个 LINQ,但是我在获得最低价格时遇到了问题:
from t1 in Table1
where
productTypes.Contains(t1.ProductType)
&&
t1.ProductHeight == 5
&&
t1.ProductWeight == 10
join t2 in Table2 on t1.ProductId equals t2.ProductId
group new { t1.ProductId, t2.ProductName }
by new { t1.ProductId, t2.ProductName } into topPrices
select new
{
ProductId = topPrices.Key.ProductId,
ProductName = topPrices.Key.ProductName,
TheCheapestPrice = ???
}
【问题讨论】: