C # LINQ for objects: help by group / amount

In the list of transaction objects, I am trying to group BatchNo and then sum the amounts.

public class Extract { // Notable fields in TRANSACTION are: String mBatchNo, String mAmount private List<Transaction> Transactions; public void testTransactions() { // Sum of amounts grouped by batch number var sGroup = from t in Transactions group t by t.mBatchNo into g select new { batchNo = g.Key, totalAmount = g.Max(a => (Int32.Parse(a.mAmount)))}; } } 

At this point, I go into the code, looking at the locals window to find out what my result set should check against the file that I imported for this object.

The last batch in the file has 3 entries, 100 pieces each, each of which can be collapsed into a transaction list object. However, drilling into the result sGroup finds the same batch to have 100 sums (should be 300). What did I mess up in this query?

Note that I saved this as a string, since we are filled with zeros to the left of the 8-character field. For export reasons, I decided to store as a string. Although this can (and probably will) be changed, it does not answer my question: how to make this request aggregate the sum into sets using BatchNo?

+6
c # linq-to-objects
source share
2 answers

You need to call Sum instead of Max :

 var sGroup = from t in Transactions group t by t.mBatchNo into g select new { batchNo = g.Key, totalAmount = g.Sum(a => (int.Parse(a.mAmount))) // Sum, not Max }; 

I would also suggest that if your mAmount field is stored as a string , to use a more robust method than int.Parse (since this will throw an exception if the string is not a valid integer, for example if it is empty). Something like that:

 int ParseOrZero(string text) { int value; if (int.TryParse(text, out value)) return value; else return 0; } var sGroup = from t in Transactions group t by t.mBatchNo into g select new { batchNo = g.Key, totalAmount = g.Sum(ParseOrZero) // blanks will be treated as 0 }; 
+16
source share

Instead of doing max, you should use the amount in your group. Right now you are setting the property only for the maximum value in the object, the sum will sum all the values ​​in the property.

+2
source share

All Articles