C# .NET - add values of column of dataset

Asked By Kapil Desai on 03-Aug-09 01:23 AM

I would like to add all the values of a column from a dataset.........

eg. a dataset contains a column salary, i wuld like to add all the values in the dataset......

Venkat K replied to Kapil Desai on 03-Aug-09 01:36 AM

if (double.TryParse(ds.tmpDT.Rows[i][2].ToString(), out tmpDbl))
                    {
                        result += tmpDbl;
                    }

ds - Dataset

tmpDT - table

Cheers!

Venkat K replied to Kapil Desai on 03-Aug-09 01:45 AM

You can use simple for loop to iterate the dataset and Calcuate the SUM for a particular column:

DataTable dt = new DataTable();  
            dt.Columns.Add("Test", typeof(String));  
            dt.Rows.Add(10);  
            dt.Rows.Add(20);  
            dt.Rows.Add(30);  
 
            // Loop  
            int sum = 0;  
            foreach (DataRow dr in dt.Rows)  
            {  
                if (dr.RowState != DataRowState.Deleted)  
                    sum += Convert.ToInt32(dr["Test"]);  
            }  
            Console.WriteLine("Sum is {0}.", sum); // Prints 60  


Cheers!

Santhosh N replied to Kapil Desai on 03-Aug-09 01:48 AM

If you are looking to display sum of a column(salary) in the grid and if that is the case then you can use compute emthod to accomplish this..

you could check here for more info..

http://programming.top54u.com/post/ASP-Net-DataTable-Compute-Column-Sum-using-C-sharp.aspx

or else, if you wish to compute the sum based on the datatable of dataset then you need to loop through and calculate (just a sample dirty code)

for ( int i = 0; i< ds1.Tables[0].Rows.Count; i++)

   totSal += ds1.Tables[0].Item[2];

re
Web Star replied to Kapil Desai on 03-Aug-09 01:54 AM
Solution :
After filling the dataset from your query you can calculate the sum of a numeric column.

Dataset's DataTable provides a default method called Compute through which you can perform any aggregate function based operation on columns in a DataTable.

Suppose you have

1. Column : Salary
2. DataSet : dsData
3. DataTable Name : Payroll

Then

dsData.Tables("Payroll").Compute("SUM(Salary)", String.Empty)

Gives the sum of that column.

Compute accepts two arguments : 1. Expression (Any aggregate Expression)
2. Filter (Any Filtering option, here String.Empty means no filter value)
Re
Ravenet Rasaiyah replied to Kapil Desai on 03-Aug-09 02:05 AM
Hi

There is two ways to this

1. you can use the looping


private void Cal()
{
double salary=0.0;

foreach (DataRow item in ds.Tables[0].Rows)
{
salary=salary+double.Parse(item["salary"].ToString()));

}

}

2. You can use the Compute method is in datatable

private void Cal()
{
object sumOfSalary=null;
sumOfSalary = ds.Tables[0].Compute("SUM(Salary)", "");

}

More detail here http://msdn.microsoft.com/en-us/library/system.data.datatable.compute.aspx

Thank you
http://www.codegain.com