Calculate difference from previous item with LINQ

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

    Yet another mod on Jon Skeet's version (thanks for your solution +1). Except this is returning an enumerable of tuples.

    public static IEnumerable<Tuple<T, T>> Intermediate<T>(this IEnumerable<T> source)
    {
        using (var iterator = source.GetEnumerator())
        {
            if (!iterator.MoveNext())
            {
                yield break;
            }
            T previous = iterator.Current;
            while (iterator.MoveNext())
            {
                yield return new Tuple<T, T>(previous, iterator.Current);
                previous = iterator.Current;
            }
        }
    }
    

    This is NOT returning the first because it's about returning the intermediate between items.

    use it like:

    public class MyObject
    {
        public int ID { get; set; }
        public DateTime Date { get; set; }
        public int Value { get; set; }
    }
    
    var myObjectList = new List<MyObject>();
    
    // don't forget to order on `Date`
    
    foreach(var deltaItem in myObjectList.Intermediate())
    {
        var delta = deltaItem.Second.Offset - deltaItem.First.Offset;
        // ..
    }
    

    OR

    var newList = myObjectList.Intermediate().Select(item => item.Second.Date - item.First.Date);
    

    OR (like jon shows)

    var newList = myObjectList.Intermediate().Select(item => new 
    { 
        ID = item.Second.ID, 
        Date = item.Second.Date, 
        DateDiff = (item.Second.Date - item.First.Date).Days
    });
    
    0 讨论(0)
提交回复
热议问题