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?
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.
Why not:
var lastValue = -1;
foreach (var item in items)
{
if (item.Value == -1)
{
item.Value = lastValue;
}
else
{
lastValue = item.Value;
}
}
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