LINQ Query to Group and Sum Data in DataTable Columns

// Assuming dt is your DataTable

This LINQ query groups the DataTable by the “Category” column and calculates the sum of the “Amount” for each category. The result is then converted into a new DataTable with columns “Category” and “TotalAmount.”

var groupedData = from row in dt.AsEnumerable()
group row by row.Field(“Category”) into grouped
select new
{
Category = grouped.Key,
TotalAmount = grouped.Sum(row => row.Field(“Amount”))
};

// Convert the result to a new DataTable or use further processing
DataTable resultDataTable = new DataTable();
resultDataTable.Columns.Add(“Category”, typeof(string));
resultDataTable.Columns.Add(“TotalAmount”, typeof(decimal));

foreach (var group in groupedData)
{
resultDataTable.Rows.Add(group.Category, group.TotalAmount);
}

Happy Automation !

1 Like