【发布时间】:2020-10-28 19:12:41
【问题描述】:
我有一个 DataPoint 对象列表(只读),其中一些具有值,而另一些为空。我想生成一个新的 DataPoint 对象列表,其中任何 null DataPoint 都设置为最接近的先前非 null 值(左侧)。如果空值之前没有非空值,则默认为 0。
在下面的示例中,前 2 个空值变为 0,因为它们之前没有非空值,最后两个空值变为 5,因为 5 是最靠近它们左侧的非空值。
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}
我能否了解如何在 LINQ 中以优雅的方式实现这一目标?谢谢
更新:为避免歧义,我已将 inputList 更新为包含 null,而不是包含 null 值的 DataPoint 实例。
【问题讨论】:
-
最后两个 null 转换为 5 不符合您的规则,它们没有以前的非 null 值。编辑 - 等等我可能读错了。是的。没关系。
-
你应该添加你到目前为止尝试过的内容。
-
为什么一定要使用 linq?使用它似乎不是一个场景
-
^ +1,为什么要使用 LINQ?您是否需要延迟执行,或者您只是对如何将 LINQ 应用于此用例感到好奇?
-
在 LINQ 中无法优雅地实现这一点,我指的是现有的内置 LINQ 方法或语法。