[英]How to SUM the value from DISTINCT row using LINQ
數據表如下:
Item CartonID Quantity
A 0001 1000
A 0002 500
A 0003 250
A 0002 500
B 0002 500
B 0003 250
我的輸出假設是這樣的:
ItemNo CartonID TotalCarton TotalQuantity
A 0001,0002,0003 3 2250
B 0002,0003 2 750
但我的結果列表如下:
ItemNo CartonID TotalCarton TotalQuantity
A 0001, 0002, 0003 3 2,250
B 0002, 0003 2 750
我的代碼列表如下:
var items = ( from item in dtTest.AsEnumerable()
group item by new
{
Item_No=item.Field<string>("Item")
}
into g
select new
{
g.Key.Item_No,
TotalCarton = (from p in dtTest.AsEnumerable()
where p.Field<string>("Item") == g.Key.Item_No
select p.Field<string>("CartonID")).Distinct().ToArray().Count(),
Total_Quantity =g.Sum((p=>p.Field<decimal>("Quantity"))).ToString("###,###,###,###"),
CartonID = (from p in dtTest.AsEnumerable()
where p.Field<string>("Item") == g.Key.Item_No
select p.Field<string>("CartonID")).Distinct().ToArray().Aggregate
((p1, p2) => p1 + ", " + p2)
}).ToList();
任何人都可以告訴我如何將總數與不同的紙箱ID相加。 提前致謝。
你應該GroupBy CartonID然后總結組元素:
這樣的事情
dtTest.GroupBy(x => x.CartonId)
.ToDictionary(y => y.Key, y => y.Sum(z => z.Quantity);
這將返回一個字典,其中包含每個CartonID的總數量。 我希望我理解正確,這就是你想要的。
基於您所說的應該檢索的輸出,我將查詢調整為:
dtTest.GroupBy(x => x.ItemNo)
.Select(itemGroup => new {
itemGroup.Key,
itemGroup.Distinct(item => item.CartonID),
itemGroup.Distinct(item => item.CartonID).Count(),
itemGroup.Sum(item => item.Quantity)
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.