I would like to get the total sum of a DataTable column in C#. However, my column consist of both string and numeric values. Is there a way to sum up only numeric values found in the column?
DataTable
Column
hello
304
-312
213
bye
I have tried using the code below but it will not work when there the cell is not in numeric value.
var total = dt.Compute("Sum(column)","");
I don't think you can use casting in Compute
so a solution could be something like this (VB.net code):
Dim dt As New DataTable
dt.Columns.Add("test")
dt.Rows.Add("hello")
dt.Rows.Add("304")
dt.Rows.Add("-312")
dt.Rows.Add("213")
dt.Rows.Add("bye")
Dim intTotal As Integer = 0
For Each dr As DataRow In dt.Rows
Dim intValue As Integer = 0
If Integer.TryParse(dr("test"), intValue) Then
intTotal += intValue
End If
Next dr
MsgBox(intTotal)
decimal sum; for (i=0;i<rows;i++) { sum += decimal.TryParse(dt["Column"][i].ToString(), out var value) ? value : (decimal)0L; }
C# example
Datatable dt = new DataTable()
dt.Columns.Add("test")
dt.Rows.Add("test2")
dt.Rows.Add("45")
dt.Rows.Add("12")
dt.Rows.Add("-213")
dt.Rows.Add("test3")
int total = 0
Foreach(DataRow dr in dt.Rows) {
If (Integer.TryParse(dr("test")){
total += dr("test").value)
}
}
return total;
The Compute method allows type conversion.
var sum = dt.Compute("Sum(Convert(column, 'System.Int32'))");
You can also use LINQ:
int sum = dt.Rows.Select(dr=>(int)dr["column"]).Sum();
For more informations: MSDN
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.