如何按间隔获取日期时间组

时间:2017-06-01 07:11:10

标签: c# intervals

我想在组中聚集DateTimes列表。 对于ins来说,每次都以30秒的间隔彼此靠近。

12:00:05,
12:00:10,
12:00:15,
12:30:15,
12:30:25

我有一个时间列表 - MainBookmarksList

MainBookmarksList.Add(dt1);
MainBookmarksList.Add(dt2);
MainBookmarksList.Add(dt3);
MainBookmarksList.Add(dt4);
MainBookmarksList.Add(dt5);

现在我希望有这样的团体

12:00:05,
12:00:10,
12:00:15,
********
12:30:15,
12:30:25

我试过了:

TimeSpan interval = new TimeSpan(0, 0, 15);

var groupedTimes = from dt in MainBookmarksList
                   group dt by dt.Ticks / interval.Ticks
                   into g
                   select new { Begin = new DateTime(g.Key * interval.Ticks), Values = g.ToList() };

但它没有返回正确的结果。

1 个答案:

答案 0 :(得分:1)

一种可能的解决方案是:

    static void Main(string[] args)
    {
        var MainBookmarksList = new List<DateTime>();
        MainBookmarksList.Add(new DateTime(1900, 1, 1, 12, 0, 5));
        MainBookmarksList.Add(new DateTime(1900, 1, 1, 12, 0, 10));
        MainBookmarksList.Add(new DateTime(1900, 1, 1, 12, 0, 15));
        MainBookmarksList.Add(new DateTime(1900, 1, 1, 12, 30, 15));
        MainBookmarksList.Add(new DateTime(1900, 1, 1, 12, 30, 25));

        var interval = new TimeSpan(0, 0, 15);

        var groupedTimes = new List<TimeGroup>();
        var currentTimeGroup = new TimeGroup(MainBookmarksList[0]);
        groupedTimes.Add(currentTimeGroup);
        for (var i = 1; i < MainBookmarksList.Count; i++)
        {
            var time = MainBookmarksList[i];
            if (time-currentTimeGroup.Begin > interval)
            {
                currentTimeGroup = new TimeGroup(time);
                groupedTimes.Add(currentTimeGroup);
            }
            else
            {
                currentTimeGroup.Values.Add(time);
            }
        }
    }

    class TimeGroup
    {
        public TimeGroup(DateTime dateTime)
        {
            Begin = dateTime;
            Values = new List<DateTime>() { dateTime };
        }

        public DateTime Begin { get; }
        public List<DateTime> Values { get; }
    }