c#lambda用GROUP BY和SUM读取每一行

时间:2015-05-14 06:35:19

标签: c# lambda group-by

这是我在管理工作室使用的工作查询。

SELECT TOP 5 productCode, SUM(productSales) AS sales
FROM     sellingLog
WHERE  (salesYear = '2014')
GROUP BY productCode
ORDER BY sales DESC

我想将上面的查询转换为lambda,但我似乎无法使其有效。 lambda仍然没有order by并选择productCode

var topProducts = sellingLog
       .Where(s => s.salesYear == 2014)
       .GroupBy(u => u.productCode)
       .Select(b => b.Sum(u => u.productSales)).Take(5)
       .ToList();

foreach(var v in topProduct)
{
   //reading 'productCode' and 'sales' from each row
}

2 个答案:

答案 0 :(得分:4)

var topProducts = sellingLog
       .Where(s => s.salesYear == 2014)
       .GroupBy(u => u.productCode)
       .Select(g => new { productCode = g.Key, sales = g.Sum(u => u.productSales) })
       .OrderByDescending(x => x.productCode)
       .Take(5)
       .ToList();

答案 1 :(得分:3)

您可以将.Key与group by一起使用以获取productCode

var topProducts = sellingLog
   .Where(s => s.salesYear == 2014)
   .GroupBy(u => u.productCode)
   .Select(b => new {u.Key, b.Sum(u => u.productSales)}).Take(5)
   .OrderByDescending(b=>b.Sales) 
   .ToList();