我想总结不同产品的qunatites。我是Linq的新手,我无法获得预期的数据。请帮忙。
我的数据表看起来像这样:
Proname | Qty1 | Qty2 | Qty3
----------------------------
A | 2 | 0 | 4
A | 0 | 4 | 5
A | 3 | 2 | 0
B | 5 | 4 | 2
C | 6 | 4 | 3
C | 1 | 1 | 1
Expected Result :
Proname | Qty1 | Qty2 | Qty3
----------------------------
A | 5 | 6 | 9
B | 5 | 5 | 5
C | 7 | 5 | 4
答案 0 :(得分:0)
这应该让你开始:
var products = new DataTable();
products.Columns.Add("ProductName", typeof(string));
products.Columns.Add("Qty1", typeof(int));
products.Columns.Add("Qty2", typeof(int));
products.Columns.Add("Qty3", typeof(int));
products.Rows.Add(new object[] {"A", 2, 0, 4});
products.Rows.Add(new object[] {"A", 0, 4, 5});
products.Rows.Add(new object[] {"A", 3, 2, 0});
products.Rows.Add(new object[] {"B", 5, 4, 2});
products.Rows.Add(new object[] {"C", 6, 4, 3});
products.Rows.Add(new object[] {"C", 1, 1, 1});
products.AsEnumerable()
.GroupBy (p => p.Field<string>("ProductName"))
.Select (p => new {
Name = p.Key,
Qty1 = p.Sum (a => a.Field<int>("Qty1")),
Qty2 = p.Sum (a => a.Field<int>("Qty2")),
Qty3 = p.Sum (a => a.Field<int>("Qty3"))
});
输出:
参考: