DeSon
DeSon

Reputation: 147

C# Datatable : Sum row values when rows having duplicate string value

Need an easy method to sum row values(int columns) when a string column value has duplicates in a datatable. And need to remove rows having duplicate values. Below is a datatable for example.

Below table have duplicate "AAA" values, so need to sum Int_Col3,Col4,Col5,Col6,Col7. Note that the columns with Int are integer columns.

Example datatable

Expected Datatable: enter image description here

Upvotes: 0

Views: 677

Answers (1)

Oguz Ozgul
Oguz Ozgul

Reputation: 7187

Here is a simple method to achieve what you want, in-place. (The same data table is converted to the expected state)

private static void CombineDuplicatesInPlace(DataTable dt)
{
    Dictionary<string, DataRow> cachedRows = new Dictionary<string, DataRow>();

    for (int i = 0; i < dt.Rows.Count; i++)
    {
        DataRow dataRow = dt.Rows[i];
        string key = Convert.ToString(dataRow["String_Col1"]);
        if (cachedRows.ContainsKey(key))
        {
            DataRow existingRow = cachedRows[key];

            foreach (DataColumn dc in dt.Columns)
                if (dc.DataType == typeof(int))
                    existingRow[dc] = (int)existingRow[dc] + (int)dataRow[dc];

            dt.Rows.Remove(dataRow);
            i--;
        }
        else { cachedRows[key] = dataRow; }
    }
}

Upvotes: 2

Related Questions