Grouping Sum Guru?

beantownace

Active member
Joined
Feb 15, 2019
Messages
40
Programming Experience
5-10
Hello all, I am struggling to make this as clean as I can the data is broken out so not easy to work with. This is what I am trying to do and thanks for any help if someone has a clean way to handle this.

I have the following prop data and it's split by top level order and then order detail rows like so:

Property Data:
public PropertyInfo
{
  public int OrderId { get; set; }
  public string PropertyName { get; set; }
  public object Value { get; set; }
}

PropertyInfo[] orders;
PropertyInfo { OrderId = 1, PropertyName = "OrderType", Value = "BUY" }
PropertyInfo { OrderId = 2, PropertyName = "OrderType", Value = "BUY" }
PropertyInfo { OrderId = 3, PropertyName = "OrderType", Value = "SELL" }

PropertyInfo[] orderDetails;
PropertyInfo { OrderId = 1, PropertyName = "GroupId", Value = "34" }
PropertyInfo { OrderId = 1, PropertyName = "Account", Value = "Travel" }
PropertyInfo { OrderId = 1, PropertyName = "Amount", Value = "5.25" }

PropertyInfo { OrderId = 2, PropertyName = "GroupId", Value = "34" }
PropertyInfo { OrderId = 2, PropertyName = "Account", Value = "Travel" }
PropertyInfo { OrderId = 2, PropertyName = "Amount", Value = "10.25" }

PropertyInfo { OrderId = 3, PropertyName = "GroupId", Value = "34" }
PropertyInfo { OrderId = 3, PropertyName = "Account", Value = "Travel" }
PropertyInfo { OrderId = 2, PropertyName = "Amount", Value = "15.50" }

What I need to check is if the order details balance so it is grouped by GroupId, Account, Sum(Amount)
If the OrderType at the top level is SELL I need to multiply by -1 the amounts will always be positive.
Bool check if valid or not.

Thanks for any help this data is painful I need to deal with.
 
You could convert orders to a dictionary by OrderId and value 1/-1 on condition "buy/sell", and use this to multiply value later.
C#:
var multiplier = orders.ToDictionary(o => o.OrderId, o => (string)o.Value == "BUY" ? 1 : -1);

Then filter orderDetails for "Amount" and Sum (Value * multiplier lookup)
C#:
var balance = orderDetails.Where(o => o.PropertyName == "Amount")
                          .Sum(o => decimal.Parse((string)o.Value) * multiplier[o.OrderId]);
 
1729406012272.png
 
Maybe a school example of one not balancing?
 
I really appreciated ChatGPT for this the other day, dumped a massive block of JavaScript into it that was mostly repetitive-ish/ the sort of code where the second and third set of functions were created from copy pasting the first one and tweaking..

And I asked it if I'd made any obvious copypasta inconsistency errors; it pointed out 4 that I'd overlooked
 
Back
Top Bottom