I currently have a method which is quite simple and calculates a list of CurveValue (custom object), the issue I have is I need to calculate the parameter and pass a decimal back without actually changing the parameter.
I tried to AddRange() into a new object so the parameter curve would not be affected but it seems the reference still exists and after the ForEach() is performed both curve, and curveA have changed.
I'm assuming it is still referenced but is there an easy way of doing this without enumerating through the parameter curve and adding it to curveA?
public decimal Multiply(List<CurveValue> curve, decimal dVal)
{
List<CurveValue> curveA = new List<CurveValue>();
curveA.AddRange(curve);
curveA.ForEach(a => a.Value = decimal.Round(a.Value, 4) * dVal);
return Sum(curveA);
}
public decimal Sum(List<CurveValue> curveA)
{
return curveA.Sum(x => x.Value);
}
You can just use the Sum method like so:
public decimal Multiply(IEnumerable<CurveValue> curve, decimal dVal)
{
return curve.Sum(a => decimal.Round(a.Value, 4) * dVal);
}
Update
Providing another implementation that passes through to the existing Sum method:
public decimal Multiply(IEnumerable<CurveValue> curve, decimal dVal)
{
IEnumerable<CurveValue> curveA = curve.Select(c => new Curve { Value = decimal.Round(c.Value, 4) * dVal });
return Sum(curveA);
}
public decimal Sum(IEnumerable<CurveValue> curveA)
{
return curveA.Sum(x => x.Value);
}
As you're using a List collection, you're able to use the Select extension method. This method provides a parameter where you define a transformation function for each element on your list and returns an IEnumerable where T is the type you specify on your function.
Hope it helps :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With