我想得到DataTable列在C#中的总和。但是,我的列包含字符串和数值。是否有一种方法只对列中的数值进行汇总?
DataTable
Column
hello
304
-312
213
bye
我试过使用下面的代码,但当单元格没有数值时,它将无法工作。
var total = dt.Compute("Sum(column)","");
发布于 2019-02-25 01:50:32
decimal sum;
for (i=0;i<rows;i++)
{
sum += decimal.TryParse(dt["Column"][i].ToString(), out var value) ? value : (decimal)0L;
}
发布于 2019-02-25 01:51:03
我不认为您可以在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)
发布于 2019-02-25 02:18:27
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;
https://stackoverflow.com/questions/54863258
复制