Ku Han
Ku Han

Reputation: 59

C# How do i merge two DataTable Row into one row

I have a datatable that looks like below which have been populated from Database

enter image description here

How can i make the result to look like below

enter image description here

Sorry for my bad explanation,Thank you very much

Upvotes: 0

Views: 354

Answers (2)

Selim Yildiz
Selim Yildiz

Reputation: 5380

If you want to do it with Datatable instead of SQL you can use:

dt = dt.AsEnumerable()
       .GroupBy(r => new {PN = r["PN"], Description = r["Description"]})
       .Select(g => 
       {  
            var row = dt.NewRow();

            row["PN"] =  g.Key.PN;
            row["Description"] = g.Key.Description;
            row["January"] =  g.Sum(r => r.Field<int>("January"));
            row["February"] =  g.Sum(r => r.Field<int>("February"));
            row["March"] =  g.Sum(r => r.Field<int>("March"));
            row["April"] =  g.Sum(r => r.Field<int>("April"));
            
            return row;
       
       })
       .CopyToDataTable();

See: How do I use SELECT GROUP BY in DataTable.Select(Expression)?

Upvotes: 0

Brimbles
Brimbles

Reputation: 11

You would need to write something like this:

Select
PN,
[Description],
Sum(January) AS January,
Sum(February) AS February,
Sum(March) AS March,
Sum(April) AS April
FROM [YourTable]
GROUP BY
PN,
[Description]

Upvotes: 1

Related Questions