将分区转换为LINQ

时间:2019-07-15 04:35:22

标签: c# sql asp.net sql-server linq

新问题:我一直在研究将查询转换为LINQ的答案。

也尝试按建议进行分组,但无法解决我的问题。我想要获得的row_number等于1。

sql:

SELECT *
FROM(
    SELECT
        RN = ROW_NUMBER() OVER(PARTITION BY p.Sku ORDER BY p.Id DESC) ,
        p.Sku
    FROM Product p
    INNER JOIN ProductAttributeCombination pac ON p.Id = pac.ProductId
    WHERE  p.Published = 1
) AS T
WHERE T.RN = 1

还有linq:

 using (var db = new NopcommerceDbContext())
 {
        var result = (
             from p in db.Products
             from pac in db.ProductAttributeCombinations.Where(pac => p.Id == pac.ProductId).DefaultIfEmpty()
             where p.Published == true
             orderby p.Id descending
             select p
    ).ToList();


       for (var x = 0; x < result.Count; x++)
       {
          Trace.WriteLine($"{ result[x].Sku}");
       }
    }

如上所述。我只希望重复记录中有1个row_number。

我尝试了@mjwills的建议,但没有得到想要的结果。 当我使用First()时,它什么也没显示。与FirstDefault()

相同

这是我更新的代码:

var items = _context.Products
              .GroupBy(g => g.Sku)
              .Select(g => g.OrderByDescending(c =>c.Sku).FirstOrDefault());

任何教程或建议将不胜感激。

1 个答案:

答案 0 :(得分:1)

使用LINQ扩展方法尝试此操作:

  var result = db.Procducts
    .Join(db.ProductAttributeCombinations, p => p.Id, pac => pac.ProductId, (p, pac) => p)
    .Where(p => p.Published == true)
    .GroupBy(p => p.Sku)
    .Select(g => g.OrderByDescending(p => p.Id).FirstOrDefault());