首页 > 解决方案 > 如何在列C#中仅添加数字

问题描述

我想获得 C# 中 DataTable 列的总和。但是,我的列由字符串和数值组成。有没有办法只总结列中找到的数值?

数据表

Column

hello
304
-312
213
bye

我尝试使用下面的代码,但是当单元格不是数值时它将不起作用。

var total = dt.Compute("Sum(column)","");

标签: c#oledboledbconnectionoledbdatareader

解决方案


我认为您不能使用强制转换,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)

推荐阅读