Search code examples
c#oledboledbconnectionoledbdatareader

How to add only numeric numbers in a column C#


I would like to get the total sum of a DataTable column in C#. 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)","");

Solution

  • decimal sum;
    for (i=0;i<rows;i++)
    {
      sum += decimal.TryParse(dt["Column"][i].ToString(), out var value) ? value : (decimal)0L;
    }