Home > front end >  Varied results on Linq list select
Varied results on Linq list select

Time:10-15

I have a simple method to calculate the growth between items in a list. Something strange is happening where the first and second dump will show different results for the first item.

Good 1000/1300/0.3.
Bad 1700/1300/-0.23.

I'm really stumped, can anyone help?

void Main()
{
    List<TestItem> items = new()
    {
        new() { EndDate = new DateTime(2020, 3, 31), CloseValue = 1300M },
        new() { EndDate = new DateTime(2020, 6, 30), CloseValue = 1600M },
        new() { EndDate = new DateTime(2020, 7, 31), CloseValue = 1700M },
    };

    var openValue = 1000M;

    var completeItems =
            items.Select(x =>
            {
                var item = new TestItem
                {
                    EndDate = x.EndDate,
                    OpenValue = openValue,
                    CloseValue = x.CloseValue,
                };

                openValue = item.CloseValue;
                return item;
            });
            
    completeItems.Dump();
    completeItems.Dump();
}

class TestItem
{
    public DateTime EndDate { get; set; }
    public decimal OpenValue { get; set; }
    public decimal CloseValue { get; set; }
    public decimal Growth => (OpenValue == 0) ? 0 : (CloseValue - OpenValue) / OpenValue;
}

CodePudding user response:

That's the reason for your confusion:

var openValue = 1000M;    

openValue = item.CloseValue;

In the first iteration, your openValue is 1000M. At the end of your first iteration, you set the openValue to the closeValue of the last item in your list, which is 1700M. Starting then a new iteration will give you an initial openValue of 1700M, which is causing the differing values for the first item. Reset the openValue before you run your function and you will be fine.

completeItems.Dump();
openValue = 1000M;
completeItems.Dump();

CodePudding user response:

There is nothing strange here - completeItems is a Linq query, when you call .Dump() on it, the query is executed and you modify the openValue variable three times, eventually assigning it 1700M (in third iteration).

When you call .Dump() another time, the query is executed again, but now openValue has a "starting" value of 1700M not 1000M. Hence the result of 1700M and negative growth in the second dump.

  • Related