You need to group the data by the first column, and then for other column calculate the sum:
using System;
using System.Data;
using System.Linq;
namespace SampleConsoleApp
{
internal class Program
{
static void Main(string[] args)
{
//Get data
var input = GetData();
//Create empty DataTable with the same structure as input
var result = input.Clone();
//Reduce data, group by the first column
//Then for each column, calculate sum
input.Rows.Cast<DataRow>().GroupBy(
row => row[0],
row => row)
.Select(group =>
{
var reduced = result.NewRow();
reduced[0] = group.Key;
for (int columnIndex = 1; columnIndex < result.Columns.Count; columnIndex++)
reduced[columnIndex] = group.Sum(row => (double)row[columnIndex]);
return reduced;
})
.ToList()
.ForEach(row =>
{
result.Rows.Add(row);
});
//Print the result
foreach (DataRow item in result.Rows)
{
var outputStr = string.Join(",", item.ItemArray.Select(x => x.ToString()).ToArray());
Console.WriteLine(outputStr);
}
Console.ReadLine();
}
static DataTable GetData()
{
var data = new DataTable();
data.Columns.Add("CostCenter", typeof(string));
data.Columns.Add("A", typeof(double));
data.Columns.Add("B", typeof(double));
data.Columns.Add("C", typeof(double));
data.Columns.Add("D", typeof(double));
data.Rows.Add("Lorem", 100, 100, 100, 100);
data.Rows.Add("Lorem", 100, 100, 100, 100);
data.Rows.Add("Lorem", 100, 100, 100, 100);
data.Rows.Add("Ipsum", 100, 100, 100, 100);
data.Rows.Add("Ipsum", 100, 100, 100, 100);
data.Rows.Add("Dolor", 100, 100, 100, 100);
return data;
}
}
}
Here is a text representation of the result:
Lorem,300,300,300,300
Ipsum,200,200,200,200
Dolor,100,100,100,100