-4

I want to sum up the qunatites for different products. I'm new to Linq and I'm not able to get the expected data. Please help.

My Datatable looks like this:

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
Marco
  • 22,856
  • 9
  • 75
  • 124
Akhil R J
  • 184
  • 2
  • 14

1 Answers1

1

This should get you started:

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"))
        });

Output:

enter image description here

Reference:

Community
  • 1
  • 1
Marco
  • 22,856
  • 9
  • 75
  • 124
  • HAi , serv thanx alot for the quick response and making corrections to my post , One more thing if i want perform group by based on multiple columns and want to display a set of colums like , proname , qty1 , qty2 , qty3 , batch and expiry on proname and batch i want to put a group by and qty1 , qty2 , qty3 i'm using aggregate function but for expiry it should display the plain text – Akhil R J Sep 29 '15 at 18:56
  • You should make this a seperate new question – Marco Sep 29 '15 at 19:40