[英]How to add only numeric numbers in a column C#
I would like to get the total sum of a DataTable column in C#. 我想获取C#中DataTable列的总和。 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): 我认为您不能在
Compute
使用强制转换,因此解决方案可能是这样的(VB.net代码):
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 C#示例
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.