[英]How to SUM the value from DISTINCT row using LINQ
Datatable as below: 数据表如下:
Item CartonID Quantity
A 0001 1000
A 0002 500
A 0003 250
A 0002 500
B 0002 500
B 0003 250
My output suppose to be this: 我的输出假设是这样的:
ItemNo CartonID TotalCarton TotalQuantity
A 0001,0002,0003 3 2250
B 0002,0003 2 750
But my result is list as below: 但我的结果列表如下:
ItemNo CartonID TotalCarton TotalQuantity
A 0001, 0002, 0003 3 2,250
B 0002, 0003 2 750
My code is list as below: 我的代码列表如下:
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();
Anyone can tell me how to sum the total with distinct Carton ID. 任何人都可以告诉我如何将总数与不同的纸箱ID相加。 Thanks in advance.
提前致谢。
You should GroupBy CartonID and then sum the groups elements: 你应该GroupBy CartonID然后总结组元素:
something like this 这样的事情
dtTest.GroupBy(x => x.CartonId)
.ToDictionary(y => y.Key, y => y.Sum(z => z.Quantity);
This will return a dictionary containing the total quantity per each CartonID. 这将返回一个字典,其中包含每个CartonID的总数量。 I hope i understood correctly that this is what you want.
我希望我理解正确,这就是你想要的。
Based on the Output that you said is supposed to be retrieved, i adapted the query to this: 基于您所说的应该检索的输出,我将查询调整为:
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.