Sum DataTable columns of type string

好久不见. 提交于 2020-01-14 19:51:13

问题


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


回答1:


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. ;-)



来源:https://stackoverflow.com/questions/708299/sum-datatable-columns-of-type-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!