LINQ aggregate and group by periods of time

后端 未结 8 2062
醉酒成梦
醉酒成梦 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:22

    I'd suggest using new DateTime() to avoid any issues with sub millisecond differences

    var versionsGroupedByRoundedTimeAndAuthor = db.Versions.GroupBy(g => 
    new
    {
                    UserID = g.Author.ID,
                    Time = RoundUp(g.Timestamp, TimeSpan.FromMinutes(2))
    });
    

    With

      private DateTime RoundUp(DateTime dt, TimeSpan d)
            {
                return new DateTime(((dt.Ticks + d.Ticks - 1) / d.Ticks) * d.Ticks);
            }
    

    N.B. I am here grouping by Author.ID as well as the rounded TimeStamp.

    RoundUp function taken from @dtb answer here https://stackoverflow.com/a/7029464/661584

    Read about how equality down to the millisecond doesn't always mean equality here Why does this unit test fail when testing DateTime equality?

提交回复
热议问题