Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataRow[] Aggregate Functions C#

Tags:

c#

aggregate

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.

like image 875
Rich Andrews Avatar asked Oct 24 '09 09:10

Rich Andrews


1 Answers

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.

like image 134
Marc Gravell Avatar answered Oct 04 '22 20:10

Marc Gravell