简体   繁体   English

如何在列C#中仅添加数字

[英]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;

The Compute method allows type conversion. Compute方法允许类型转换。

var sum = dt.Compute("Sum(Convert(column, 'System.Int32'))");

You can also use LINQ: 您也可以使用LINQ:

int sum = dt.Rows.Select(dr=>(int)dr["column"]).Sum();

For more informations: MSDN 有关更多信息: MSDN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM