Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing values with LINQ in a list with the previous value matching some criterion

Tags:

linq

I have produced a list of two values.

Id Value
10  0 
11  1 
12  2 
13  3 
14 -1 
15 -1 
16  6 
17 -1 
18  8 
19  9 

I would like all -1 values to be replaced with the previous not -1 value such that I end up with the list

Id Value
10  0 
11  1 
12  2 
13  3 
14  3 
15  3 
16  6 
17  6 
18  8 
19  9 

Is there a cool way of doing this in LINQ?

like image 279
kasperhj Avatar asked Dec 02 '25 12:12

kasperhj


2 Answers

If you need to access previous elements with LINQ a loop might be more appropriate (readable,efficient).

However (Obj is your class):

list = list.Select((x, index) => 
{
    if (index != 0 && x.Value == -1)
    {
        x.Value = list.Take(index)
            .Where(xPrev => xPrev.Value != -1)
            .Select(xPrev => xPrev.Value)
            .DefaultIfEmpty(int.MinValue)
            .Last();
    }
    return x;
}).ToList();

Note that this does not ensure that you get a different value than -1 since i'm just selecting the previous.

like image 53
Tim Schmelter Avatar answered Dec 06 '25 23:12

Tim Schmelter


Why not:

var lastValue = -1;
foreach (var item in items)
{
    if (item.Value == -1)
    {
        item.Value = lastValue;
    }
    else
    {
        lastValue = item.Value;
    }
}
like image 39
Vladimir Avatar answered Dec 06 '25 21:12

Vladimir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!