c# - 如何在列C#中仅添加数字
问题描述
我想获得 C# 中 DataTable 列的总和。但是,我的列由字符串和数值组成。有没有办法只总结列中找到的数值?
数据表
Column
hello
304
-312
213
bye
我尝试使用下面的代码,但是当单元格不是数值时它将不起作用。
var total = dt.Compute("Sum(column)","");
解决方案
我认为您不能使用强制转换,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)
推荐阅读
- winapi - 等待由 IShellDispatch2.ShellExecute 启动的进程
- java - 使用 Kafka 流的本地增量值映射
- flutter - 如何检测颤动中的滑动
- laravel - 评论 @extends('layouts.app') 不起作用
- java - Leetcode1002. 查找字符串之间的公共字符 -Java
- r - 尝试写入永久表时,copy_to 不适用于非默认模式
- javascript - 如何访问此 JSON 层次结构中的子节点?
- excel - 确定是否按下了取消按钮,其中 InputBox 变量声明为 Double
- sparql - SPARQL 可选未绑定 VS 过滤器不存在
- php - 如何读取 Amazon SNS JSON 响应