使用LINQ for Group和Sum

时间:2015-12-28 21:24:12

标签: c# linq entity-framework-6

我无法从linq查询中获取分组总和。我试图在特定日期范围之间获得产品的净变化。现在我的查询运行并带回每笔交易的总数量变化,但我无法得到总和。我的查询如下:

from t in Transactions
join p in Products on t.Product.ID equals p.ID
where t.TransactionDate >= DateTime.Parse("12/01/2015") && t.TransactionDate <= DateTime.Parse("12/31/2015")
orderby p.ProductCode
select new 
{
    Product = p.ProductCode,
    Description = p.Description,
    TotalQuantityChanged = (t.TransactionType.AddRemove == "Addition" ? (t.FullQuantity + (t.PartialQuantity / p.Pieces)).ToString() : (-1 * (t.FullQuantity + (t.PartialQuantity / p.Pieces))).ToString() )
}

然后返回

Product     Description                         TotalQuantityChanged

B107        3 ½" x 11" x 105" Kraft Faced R-11          23 
B107        3 ½" x 11" x 105" Kraft Faced R-11          -16 
X13AK       3 ½" x 11" x 105" Kraft Faced R-13          65 
X13AK       3 ½" x 11" x 105" Kraft Faced R-13          45 
X13AK       3 ½" x 11" x 105" Kraft Faced R-13          -12 
X45EX       3 ½" x 15" x 105" Kraft Faced R-15 HD       3 
X45EX       3 ½" x 15" x 105" Kraft Faced R-15 HD       36 
X45EX       3 ½" x 15" x 105" Kraft Faced R-15 HD       -7 

但是我已经尝试了各种各样的小组,并且没有运气。这就是结果应该是这样的:

Product     Description                         TotalQuantityChanged

B107        3 ½" x 11" x 105" Kraft Faced R-11          7 
X13AK       3 ½" x 11" x 105" Kraft Faced R-13          98 
X45EX       3 ½" x 15" x 105" Kraft Faced R-15 HD       32

我尝试过这样的分组,但是我的where子句和select语句中出现错误。

from t in Transactions
join p in Products on t.Product.ID equals p.ID 
group p by new { 
        p.ProductCode, 
        p.Description 
    } into g
where t.TransactionDate >= DateTime.Parse("12/01/2015") && t.TransactionDate <= DateTime.Parse("12/31/2015")
select new
{
    Product = g.Key.ProductCode,
    Description = g.Key.Description,
    TotalQuantityChanged = (t.TransactionType.AddRemove == "Addition" ? (t.FullQuantity + (t.PartialQuantity / p.Pieces)).ToString() : (-1 * (t.FullQuantity + (t.PartialQuantity / p.Pieces))).ToString() )
}

我不明白如何分组或获得总和。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

这大致是您的目标:

from t in Transactions
join p in Products on t.Product.ID equals p.ID
where t.TransactionDate >= DateTime.Parse("12/01/2015") && t.TransactionDate <= DateTime.Parse("12/31/2015")
group t.TransactionType.AddRemove == "Addition" 
           ? t.FullQuantity + (t.PartialQuantity / p.Pieces) 
           : -1 * (t.FullQuantity + (t.PartialQuantity / p.Pieces)) 
    by new {p.ProductCode, p.Description} into g
select new 
{
    Product = g.Key.ProductCode,
    Description = g.Key.Description,
    TotalQuantityChanged = g.Sum().ToString()
}