set the null value to the closest last non-null value in a list – linq

Use a helper extension method that is a variation of my LINQ implementation of the APL scan operator (like Aggregate but returns intermediate results) that uses a helper function to start the result stream:

// First PrevResult is TRes seedFn(T FirstValue)
// TRes combineFn(TRes PrevResult, T CurValue)
public static IEnumerable<TRes> Scan<T, TRes>(this IEnumerable<T> items, Func<T, TRes> seedFn, Func<TRes, T, TRes> combineFn) {
    using (var itemsEnum = items.GetEnumerator()) {
        if (itemsEnum.MoveNext()) {
            var prev = seedFn(itemsEnum.Current);

            while (itemsEnum.MoveNext()) {
                yield return prev;
                prev = combineFn(prev, itemsEnum.Current);
            yield return prev;

You can scan along the initial List<DataPoint> and return the previous result for any nulls, initializing with the first value, or 0 if it is null:

var ans = InputList.Scan(firstDP => firstDP ?? 0, (prevRes, curDP) => curDP ?? prevRes).ToList();

NOTE: If you don’t want to use a helper method, and are willing to abuse LINQ a little by having outside state (e.g. a helper variable), you can simply do:

var prevNonNull = new DataPoint(0);
var ans2 = InputList.Select(n => prevNonNull = n ?? prevNonNull).ToList();

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top