Calculate difference from previous item with LINQ

后端 未结 7 555
你的背包
你的背包 2020-11-27 14:50

I\'m trying to prepare data for a graph using LINQ.

The problem that i cant solve is how to calculate the \"difference to previous.

the result I expect is <

7条回答
  •  生来不讨喜
    2020-11-27 15:25

    Modification of Jon Skeet's answer to not skip the first item:

    public static IEnumerable SelectWithPrev
        (this IEnumerable source, 
        Func projection)
    {
        using (var iterator = source.GetEnumerator())
        {
            var isfirst = true;
            var previous = default(TSource);
            while (iterator.MoveNext())
            {
                yield return projection(iterator.Current, previous, isfirst);
                isfirst = false;
                previous = iterator.Current;
            }
        }
    }
    

    A few key differences... passes a third bool parameter to indicate if it is the first element of the enumerable. I also switched the order of the current/previous parameters.

    Here's the matching example:

    var query = list.SelectWithPrevious((cur, prev, isfirst) =>
        new { 
            ID = cur.ID, 
            Date = cur.Date, 
            DateDiff = (isfirst ? cur.Date : cur.Date - prev.Date).Days);
        });
    

提交回复
热议问题