Xavier Dennis Xavier Dennis - 3 years ago 214
C# Question

Invalid usage of aggregate function Sum() and Type: String

I have a data table and a column contains int values. I have not specified the column with any datatype. When I perform the following.

object sum = dttest.Compute("sum(Value)", "");

I am getting below error.

Invalid usage of aggregate function Sum() and Type: String.

And I tried converting column value to int using

object sum = dttest.Compute("sum(Convert(Value, 'System.Int32'))","");

again I am getting another error

Syntax error in aggregate argument: Expecting a single column argument
with possible 'Child' qualifier.

When I specify the datatype for the column, first code will return correct value. But in my case I can't specify column datatype. Any one having solution ?

Answer Source

You can use LINQ to Datatable:

 var result = dttest.AsEnumerable()
                    .Sum(x => Convert.ToInt32(x["Value"]));

Example how to Sum for specific name:

 var result = dttest.AsEnumerable()
                    .Where(r => r.Field<string>("Name") == "FilterName")
                    .Sum(x => Convert.ToInt32(x["Value"]));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download