Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum DataTable columns of type string

Tags:

c#-2.0

How do I calculate Sum of two rows in DataTable which is of type string ?
in my case I cannot change column type.
I tried these :

1)

object objSum;    
objSum = dt.Compute("Sum(WeightRate)", "");     

2)

decimal total = (decimal)dt.Compute("SUM( [WeightRate] )", "");`   

But no luck...

My table :

Weightrate No.Ofvehicles
350.50 50
205.00 40

I need result as

Weightrate No.Ofvehicle
555.50 90

like image 725
Guddu Avatar asked Mar 01 '23 21:03

Guddu


1 Answers

The Compute method allows for some rudimentary type conversion:

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

See the MSDN help on DataColumn Expressions for more information about what you can do with a Compute method call.

Edit Having re-read your question, you'll probably want to convert to System.Decimal rather than System.Int32, but hopefully you got that. ;-)

like image 84
Matt Hamilton Avatar answered Mar 03 '23 09:03

Matt Hamilton