0
votes

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

1
Is this an in-memory data table? - Oguz Ozgul
@OguzOzgul - Yeah! - DeSon
What will happen to String_Col2 and String_Col8 when merging, if they have different values? - Oguz Ozgul
See my answer froom posting this week : stackoverflow.com/questions/61520333/… - jdweng

1 Answers

1
votes

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; }
    }
}