You must Sign In to post a response.
  • Category: .NET

    Sum the values of duplicate records from DataTable


    I have DataTable which is having the duplicate records only (already i have pull out the duplicate rows). I want to sum all the column value and make it as single record.

    Note: the columns are added dynamically hence i couldn't do it. Can any one suggest me. I am doing this in C# coding not in SQL

    for example:

    Name PriceUnit PO-11-29-2016(Quantity) PO-11-29-2016(Price)
    Gopi 100 1 100
    Arun 100 10 1000
    Gopi 100 5 500
    Mani 100 1 100
    Mani 100 1 100

    Output Should be

    Name PriceUnit PO-11-29-2016(Quantity) PO-11-29-2016(Price)
    Gopi 100 6 600
    Arun 100 10 1000
    Mani 100 2 200
  • #768956
    You can use this code snippet to Sum the values of records group by from DataTable using LINQ

    Dictionary<string, int> dicSum = new Dictionary<string, int>();
    foreach (DataRow row in dt.Rows)
    string group=row["Group"].ToString();
    int rate=Convert.ToInt32(row["Rate"]);
    if (dicSum.ContainsKey(group))
    dicSum[group] += rate;
    dicSum.Add(group, rate);
    foreach (string g in dicSum.Keys)
    Console.WriteLine("SUM({0})={1}", g, dicSum[g]);

  • Sign In to post your comments