none
DataTable - sum values of a column RRS feed

  • Question

  • hello ,

      I have a DataTable which contains these Columns :

               ( ProductName , Price )


     I want to sum all values in the column  " Price "  in one line  by C# code .



       thanks


       hema
    ASk
    Tuesday, December 30, 2008 10:52 AM

Answers

  • You should use Compute function provided in datatable for that.

    -- Please mark it as asnwer if it solves the problem.
    • Proposed as answer by Akshay S Bhatnagar Tuesday, December 30, 2008 12:39 PM
    • Marked as answer by himo Tuesday, December 30, 2008 2:22 PM
    Tuesday, December 30, 2008 12:39 PM

All replies

  • Hi Himo,
    You have to iterate through the datatable row by row and add the values of the Price column.

    Psudo Code,

    int sum=0;
    foreach(datarow row in MydataTable.rows)
    {
        sum=sum+Convert.Int32( row[1]) // you have to convert the value in to integer
    }




    Plz mark as answer if you have got what you were looking for

    To Be A Good Programmer You Have To Be A Good Man First
    Tuesday, December 30, 2008 11:29 AM
  • Hello  ,

      I know this solution . But this question I have had an interview .

       Thanks
    ASk
    Tuesday, December 30, 2008 11:53 AM
  • You should use Compute function provided in datatable for that.

    -- Please mark it as asnwer if it solves the problem.
    • Proposed as answer by Akshay S Bhatnagar Tuesday, December 30, 2008 12:39 PM
    • Marked as answer by himo Tuesday, December 30, 2008 2:22 PM
    Tuesday, December 30, 2008 12:39 PM
  • Hi,

    You can do SUM by using LINQ in one step

    var sum = datatable.AsEnumerable().Sum(x=>x.Field<int>("Price"));


    PS.Shakeer Hussain

    Friday, June 15, 2012 6:43 PM