Problem copying AddRange () and LINQ

I currently have a method that is quite simple and computes a CurveValue list (user object), the problem I have is that I need to calculate the parameter and pass the decimal fraction without actually changing the parameter.

I tried to add AddRange () to the new object, so that the parameter curve will not be affected, but it seems that this link still exists, and after the ForEach () function is executed, both the curve and the curve change.

I assume it still references, but is there an easy way to do this without listing through the parameter curve and adding it to curve A?

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);
}
+5
source share
3 answers

Sum :

public decimal Multiply(IEnumerable<CurveValue> curve, decimal dVal)
{
    return curve.Sum(a => decimal.Round(a.Value, 4) * dVal);
}

, Sum:

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);
}
+6

List, Select. , IEnumerable, T - , .

, :)

+3

It may be a little old school, but why are you even copying a range?

You can simply iterate over the curve and put the calculated value in the list of results, and then sum the values ​​up.

List<CurveValue> curveA = new List<CurveValue>();        
curve.ForEach(a => curveA.Add(new CurveValue {Value = decimal.Round(a.Value, 4) * dVal });          

return Sum(curveA); 

Sorry, without checking the code, I'm here on my netbook. I hope you understand what I mean.

+3
source

All Articles