如何通过 join 和 group by 在 C# Linq 中获取 Min?

How to get Min in C# Linq with join and group by?

我想为以下场景构建 Linq 查询:

Table 1

PriceId
ProductId
ProductPrice 
ProductHeight
ProductWeight
ProductType

Table 2

ProductId
ProductName

任务: Select 最便宜的产品价格和名称:

最终预期结果是这样的对象列表:

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 = ???
}

您需要将您的群组调整为 return t1 记录,因为您想要访问其 ProductPrice 属性:

group t1 by new { t1.ProductId, t2.ProductName } into topPrices

然后你只需要在 topPrices 组上执行 Min,就像这样:

TheCheapestPrice = topPrices.Min(t => t.ProductPrice)

Link to working fiddle.

HTH