Computing function for strings

As we know, with the datatable computational function we can get the sum of the columns. But I want to get the sum of the datatable string. I will explain with an example:

I have a data type similar to datatable: Using the calculation function we can get the sum of each column (product). For example, for a product 1, 2 + 12 + 50 + 13 = 77.

I want to get the amount of the company 1: 2 + 6 + 4 + 3 + 5 = 20

http://img123.imageshack.us/img123/1517/61519307xx5.jpg

How can I do this using asp.net 1.1?

+4
source share
3 answers

LINQ to the rescue:

DataTable dt = WhateverCreatesDataTable(); DataRow dr = dt.Rows[0]; int sum = dt.Columns.Cast<DataColumn>().Sum(dc=>(int)dr[dc]); 

For those who still pull their joints into the stone ages (aka pre-.Net 3.5 and LINQ):

 DataTable dt = WhateverCreatesDataTable(); DataRow dr = dt.Rows[0]; int sum = 0; foreach(DataColumn dc in dt.Columns) sum += (int)dr[dc]; 
+2
source

From msdn :

If you must perform an operation on two or more columns, you must create a DataColumn, set its expression property to the corresponding expression, and use the aggregated expression on the resulting column. In this case, the given DataColumn with the name "total", and the Expression property set to this:

"Quantity * UnitPrice"

+2
source

Since you want to solve this in 1.1, here is what you can do as a simple solution

 DataColumn totalColumn = new DataColumn(); totalColumn.DataType = System.Type.GetType("System.Int32"); totalColumn.ColumnName = "Total"; totalColumn.Expression = "Product1 + Product2 + Product3 + Product4 + Product5"; // Populate and get the DataTable dt then add this computed column to this table dt.Columns.Add(totalColumn); //Now if you access the column "Total" of the table you will get the desired result. 
+2
source

All Articles