var dt = new DataTable();
dt.Columns.Add("DecCol1", typeof(decimal));
dt.Columns.Add("StrCol1");
dt.Rows.Add(new object[] { 1.1, "r1"});
dt.Rows.Add(new object[] { 2.2, "r2" });
dt.Rows.Add(new object[] { 3.3, "r3" });
object sum = dt.Compute("SUM(DecCol1)", "");
Console.WriteLine(sum);
I get the correct answer: 6.6
Compute method can calculate Sum, Average, Count and … of a specific column. It’s syntax is like this:
DataTable.Compute (string expression, string filter)
expression contains an aggregate function like Sum, Average, Count and etc. For example to calculate the total cost you must use SUM(COST) as your expression.
If you must perform an operation on two or more columns, you should create a DataColumn, set its Expression property to an appropriate expression, and use an aggregate expression on the resulting column. In that case, given a DataColumnwith the name “total,” and the Expression property set to
------------
int sum = 0;
foreach(DataRow dr in dataTable.Rows)
{
sum += Convert.ToInt32(dr["Amount"]);
}
If you want to query the database table, you could use
Select Sum(Amount) From DataTable
No comments:
Post a Comment