DataRow[] Aggregate Functions C#
Asked Answered
G

2

5

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.

Grimsley answered 24/10, 2009 at 9:51 Comment(1)
Can you please share how you initialized the rows object, used in Marc Gravell's snippet?Muskogean
R
14

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.

Ridge answered 24/10, 2009 at 9:54 Comment(5)
Sorry I'm probably being really dumb here but haven't used LINQ before :) How do you get a reference to the row if I'm not iterating through the array?Grimsley
The Sum method does the iteration. The " row => row.SomeColumn " (etc) could be interpreted as "given a row, do this", and is a delegate that is evaluated for each row. So in this case, it says "for each row, evaluate row.SomeColumn, summing them".Ridge
(so each time the "row => row.SomeColumn" operates, row is a different DataRow, if you see what I mean)Ridge
Add a link to some LINQ to Object documentation :)Coxcombry
@Marc Gravell: I have a very similar requirement as the OP. Can you please show how you initalized the variable "rows" in your example? All I have is mydataset.Tables[0].Rows collection. Thank you.Muskogean
L
0

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);
Lehmann answered 19/11, 2019 at 6:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.