DataRow[] Aggregate Functions C#

杀马特。学长 韩版系。学妹 提交于 2020-01-14 10:32:37

问题


I have an array of DataRow objects in my C# project which I would like to Sum various fields from.

Instead of running through each row and totalling my own sums I noticed the DataRow[].Sum<> function but I am struggling to find any resources on the net on how to use it.

Any pointers in the right direction would be very helpful

:) Removed code example as it was wrong! All now works fine - the link helped cheers Marc.


回答1:


That is the LINQ Sum; and can be used:

var sum = rows.Sum(row => row.Field<int>("SomeColumn")); // use correct data type

(you can also pass in the column index or the DataColumn in place of the string)

for untyped datarows, or:

var sum = rows.Sum(row => row.SomeColumn);

for typed datarows.

MSDN has full documentation on this; for example, here is the overload I am using in the examples above.




回答2:


This is my way to use sum number fields in DataRow of Datatable.

I share for whom concern.

DataTable retrieveData = GetData();
decimal value = 0;
var total = retrieveData.Rows[i].ItemArray.Sum(row => 
    decimal.TryParse(row.ToString(), out value) ? decimal.Parse(row.ToString()) : 0);


来源:https://stackoverflow.com/questions/1617518/datarow-aggregate-functions-c-sharp

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