Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AddRange() and LINQ copying issue

Tags:

c#

.net

linq

sum

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);
}
like image 323
nik0lai Avatar asked Jan 11 '12 14:01

nik0lai


2 Answers

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);
}
like image 99
Rich O'Kelly Avatar answered Sep 27 '22 20:09

Rich O'Kelly


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 :)

like image 36
Rodrigo Vedovato Avatar answered Sep 27 '22 20:09

Rodrigo Vedovato