LINQ Query to Group and Sum Data in DataTable Columns

Hello Members,

I have a Data Table with columns “Category” and “Amount,” and I want to group the data by “Category” and calculate the sum of the “Amount” for each category. How can I achieve this using LINQ in UiPath Studio? Can someone provide a sample LINQ query for grouping and summing columns in a Data Table?

// 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

Hi @abhinay_gummula

result = dt.AsEnumerable() _
    .GroupBy(Function(row) row.Field(Of String)("Category")).Select(Function(group) New With {
   .Category = group.Key, .TotalAmount = group.Sum(Function(row) row.Field(Of Decimal)("Amount"))
    })
1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.