【问题标题】:How to get Min in C# Linq with join and group by?如何通过 join 和 group by 在 C# Linq 中获取 Min?
【发布时间】: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 = ???
}

【问题讨论】:

    标签: c# linq join group-by min


    【解决方案1】:

    您需要调整您的组以返回 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

    【讨论】:

    • 这与发布的工作 SQL 查询 OP 不同。请注意,OP 分组的字段与过滤字段不同。
    • @TomK 查看更新的答案。调整组以返回整个 t1 记录后,您可以访问其价格属性并对其执行 Min
    • @Flater 不确定您的意思,它返回多个价格,每个组的最低价格。请参阅工作示例:dotnetfiddle.net/q3rDEf
    • @jcruz 谢谢,您的回答解决了我的问题。你知道我可以在哪里读到这种方法为什么有效吗?
    • @TomK 简而言之,在 Linq 中执行 group 时,您指定了分组记录的投影。网上资源很多,这里有很多例子:docs.microsoft.com/en-us/dotnet/csharp/linq/group-query-results
    猜你喜欢
    • 1970-01-01
    • 2016-04-27
    • 2012-10-26
    • 2011-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-07
    • 2011-03-20
    相关资源
    最近更新 更多