How to sum values in a column from a datatable?

Hi,
I want to sum all values in a column in a data table.
I tried to assign
MyDT.Compute(“SUM(ColumnName)”, “”).ToString and
MyDT.AsEnumerable.Sum(Function(a)Convert.ToDouble(a(“ColumnName”).ToString))

But I get System.InvalidOperationException error in both cases.
How can I solve this?

HI @makboga

Check out this expression

(From d in dtData.AsEnumerable Where Not (isNothing(d("ColumnName")) OrElse String.IsNullorEmpty(d("ColumnName").toString.Trim)) Select v = CDbl(d("ColumnName").toString.Trim)).Sum(Function (x) x)

Regards
Gokul

HI @makboga

Check out the XAML file

SumExcelColumn.xaml (12.9 KB)

image

Regards
Gokul

In my data table there is hyphen end of the number. I have to remove that symbol and then sum.
image

Can you share the sample excel file? @makboga

I extracted a data table from a web page and it is like this
image
I want to sum all values from “Tutar” column.

Hi @makboga

This expression is to remove the - from the Amount column

DtRead.AsEnumerable.Select(Function(r) DtRead.Clone.LoadDataRow({System.Text.RegularExpressions.Regex.Replace(r("Amount").ToString,"\W$","")},False)).CopyToDataTable

This expression is to sum the value in the Amount column

(From d in DtRemove.AsEnumerable Where Not (isNothing(d(0)) OrElse String.IsNullorEmpty(d(0).toString.Trim)) Select v = Double.Parse(d(0).toString.Trim,System.Globalization.CultureInfo.CreateSpecificCulture("Es-es"))).Sum(Function (x) x)

Check out this XAML file

SumExcelColumn.xaml (16.2 KB)

image

Regards
Gokul

Thank you so much @Gokul001 :slight_smile:

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.