I have a list of DataPoint objects (read-only) where some have a Value but others are null. I would like to produce a new list of DataPoint objects where any null DataPoint is set to the closest preceding non-null value (to the left). If no non-null values precede the null value then it defaults to 0.
In the example below the first 2 nulls become 0 since no non-null values preceded them and the last two nulls becomes 5 because 5 is the closest non-null value to their left.
public class DataPoint
{
public DataPoint(int inputValue)
{
this.Value = inputValue;
}
public int Value {get;}
}
Input:
List<DataPoint> inputList = new List<DataPoint>
{null,
null,
new DataPoint(1),
new DataPoint(2),
new DataPoint(3),
null,
null,
new DataPoint(4),
new DataPoint(5),
null,
null};
Expected Output:
foreach (var item in outputList)
{
Console.WriteLine(item.Value);
}
{0, 0, 1, 2, 3, 3, 3, 4, 5, 5, 5}
Can I get some idea on how to achieve this in elegant way in LINQ? thanks
UPDATE: To avoid ambiguity, I've updated inputList to contains null, instead of DataPoint instance with null value.