Calculate difference from previous item with LINQ

后端 未结 7 553
你的背包
你的背包 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:30

    Further to Felix Ungman's post above, below is an example of how you can achieve the data you need making use of Zip():

            var diffs = list.Skip(1).Zip(list,
                (curr, prev) => new { CurrentID = curr.ID, PreviousID = prev.ID, CurrDate = curr.Date, PrevDate = prev.Date, DiffToPrev = curr.Date.Day - prev.Date.Day })
                .ToList();
    
            diffs.ForEach(fe => Console.WriteLine(string.Format("Current ID: {0}, Previous ID: {1} Current Date: {2}, Previous Date: {3} Diff: {4}",
                fe.CurrentID, fe.PreviousID, fe.CurrDate, fe.PrevDate, fe.DiffToPrev)));
    

    Basically, you are zipping two versions of the same list but the first version (the current list) begins at the 2nd element in the collection, otherwise a difference would always differ the same element, giving a difference of zero.

    I hope this makes sense,

    Dave

提交回复
热议问题