2017-06-01 166 views
-2

我想將羣組中的日期時間列表羣集化。 每隔30秒的時間間隔,ins。如何按時間間隔獲取日期時間組

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

一個可能的解決辦法是這樣的:

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; } 
    } 
+0

完美!謝謝! –