cancel
Showing results for 
Search instead for 
Did you mean: 

Sum column in collection - C# code stage

KarinaHansen
Level 3
Hi

I'm looking to summarize all values in a specified column in a collection through a code stage (not looping).

In this collection called "Collection", I want a sum of all values in column "Numbers" in a data item.
1612435555473.png

I don't read or write C# very well, so can someone provide a code that will work for this?
I tried to use the compute method, with no luck (MSDN).

private void ComputeBySalesSalesID(DataSet dataSet) 

{ 
   DataTable table; 
   table = dataSet.Tables["Collection"]; 

   object sumObject; 
   sumObject = table.Compute("Sum(Numbers)", ""); 
}

Thanks a lot!
1 BEST ANSWER

Helpful Answers

NicholasZejdlik
Level 9
I find it easier to use Linq myself - here's a code stage that should do what you're looking for:
// Inputs: 
// Collection (collection)
// Column Name (text)
// 
// Outputs:
// Total (number)
//
Total = Collection.AsEnumerable().Sum(x => (decimal)x[Column_Name]);​

I had to include System.Linq and System.Data.DataSetExtensions in the namespaces on the global code tab, as well as a reference to System.Linq.dll and System.Core.dll.


View answer in original post

4 REPLIES 4

NicholasZejdlik
Level 9
I find it easier to use Linq myself - here's a code stage that should do what you're looking for:
// Inputs: 
// Collection (collection)
// Column Name (text)
// 
// Outputs:
// Total (number)
//
Total = Collection.AsEnumerable().Sum(x => (decimal)x[Column_Name]);​

I had to include System.Linq and System.Data.DataSetExtensions in the namespaces on the global code tab, as well as a reference to System.Linq.dll and System.Core.dll.


KarinaHansen
Level 3
Thanks for your answer @Nicholas Zejdlik!

I get this ​error: Compiler error at line 1: Unexpected character '​'

You got any ideas for this?

NicholasZejdlik
Level 9
Is the language set to C#? I get a similar compiler error if I'm using VB as the language instead of C#. If it is set to C#, perhaps try typing it out manually? Maybe copy/paste got some odd unicode character in there.

The VB equivalent would be this: Total = Collection.AsEnumerable().Sum(Function (x) CType(x(Column_Name), Decimal))

KarinaHansen
Level 3
You were absolutely right! I typed it in instead of copy/pasting and the error disappeared.

But then I got a reference error. I googled for a while and found out that System.Data.DataSetExtensions.dll had to be added too.

It works now! Thanks a bunch 🙂