LINQ aggregate and group by periods of time

后端 未结 8 2063
醉酒成梦
醉酒成梦 2020-11-28 06:28

I\'m trying to understand how LINQ can be used to group data by intervals of time; and then ideally aggregate each group.

Finding numerous examples with explicit dat

8条回答
  •  执笔经年
    2020-11-28 07:07

    Even though I am really late, here are my 2 cents:

    I wanted to Round() the time values down AND up in 5 minute intervals:

    10:31 --> 10:30
    10:33 --> 10:35
    10:36 --> 10:35
    

    This can be achieved by converting to TimeSpan.Tick and converting back to DateTime and using Math.Round():

    public DateTime GetShiftedTimeStamp(DateTime timeStamp, int minutes)
    {
        return
            new DateTime(
                Convert.ToInt64(
                    Math.Round(timeStamp.Ticks / (decimal)TimeSpan.FromMinutes(minutes).Ticks, 0, MidpointRounding.AwayFromZero)
                        * TimeSpan.FromMinutes(minutes).Ticks));
    }
    

    The shiftedTimeStamp can be used in linq grouping as shown above.

提交回复
热议问题