I have a tree constructed using a TreeNode class where each node has an Amounts object. The Amounts object is a simple class that houses some decimal values. E.g.
public class Amounts
{
public decimal Amount1 { get; set; }
public decimal Amount2 { get; set; }
...
}
I need to be able to perform some code for each individual property independently, and what I'd like to do is somehow pass one of the Amounts properties to this method using a lambda or similar but I can't quite work out how to do this (I've been a while off the tools unfortunately). I don't particularly like the idea of passing a property name string so I can use reflection SetPropertyValue method.
I want the traversal method to look something like the below. I'm aware that Linq supports a Sum method but I have just used this as a simplified example, with the actual calculation performed being more complex.
public void Traverse(Func<ContributionAmounts, decimal> getter)
{
foreach (var child in this.Children)
{
getter(this.Amounts) += getter(child.Amounts);
}
}
Rather than having a separate method for each amount, I'd like to do be able to call it something like below:
Traverse(a => a.Amount1);
Traverse(a => a.Amount2);
The code above does not work as the value returned by the Func is a read-only decimal value, rather than the decimal property (e.g. Amount1).
I'm not sure if I have explained the requirement very well, but hopefully enough to get a pointer in the right direction.
Thanks, John