LINQ : Group by Multiple Columns with Maximum for one column

本文关键字:Maximum for one column with Columns Group by Multiple LINQ | 更新日期: 2023-09-27 18:13:39

我有查询下面的SQL。尝试在linq中使用不同的选项来获得从SQL到我的中心代码的精确匹配结果,这里是我使用linq的代码。

但不能得到它。

SQL查询是(给出正确的结果)

Select prdCode, Max(prdID) from products 
    GROUP BY prdCode
    order by prdCode

在linq

from prd in Entities.Products
    where prd.prdEnabled == true
    group prd by new { prd.prdCode, prd.prdID } into gcs 
    select new { prdID = gcs.Key.prdID, prdCode = gcs.Key.prdCode }

LINQ : Group by Multiple Columns with Maximum for one column

from prd in Entities.Products
where prd.prdEnabled == true
group prd by prd.prdCode into gcs 
orderby gcs.Key
select new { prdCode = gcs.Key, prdID= gcs.Max(g => g.prdID) }

这应该匹配您的SQL查询

Entities.Producs.Where(prod=> prod.prdEnabled)
                .GroupBy(prod => prod.prdCode)
                .Select(group => new{ prdCode = group.Key, prdID = group.Max(prod => prod.prdID) } )
                .OrderBy(x => x.prdCode);
  1. 根据产品的prdEnabled属性筛选
  2. 按产品代码
  3. 进行分组
  4. 对于每一组,选择代码和最大id
  5. 按代码排序