2013-11-25 64 views
2

下面是我列出組連續的元素,選擇第一和最後一個元素

List<DateTime> ls_date =new List<DateTime>() 
ls_date.Add("2013-12-02") 
ls_date.Add("2013-12-03") 
ls_date.Add("2013-12-04") 
ls_date.Add("2013-12-05") 
ls_date.Add("2013-12-08") 
ls_date.Add("2013-12-12") 
ls_date.Add("2013-12-13") 
ls_date.Add("2013-12-14") 

我想組連續的日期並選擇開始和該組

輸出的結束日期:

"2013-12-02"-"2013-12-05" 
"2013-12-08"-"2013-12-08" 
"2013-12-12"-"2013-12-14" 

我的嘗試:

public class sampleWithIntervals 
{ 
public DateTime startDate; 
public DateTime endDate; 
} 
    var data = ls_date 
      .Select((s, i) => new { sample = s, index = i })     
      .GroupBy(si => new { date = si.sample.Date.AddDays(-si.index) })     
      .Select(g => new sampleWithIntervals() 
      { 
       startDate = g.Min(s => s.sample.Date), 
       endDate = g.Max(s => s.sample.Date) 

      }); 

我怎樣才能做到這一點?

+0

您可以從我的(http://codereview.stackexchange.com/questions/6512/grouping-by-sequence-in-linq)函數或其中一個答案開始。 – MPelletier

+0

'List ls_date = new List (); ls_date.Add(「2013-12-02」);'不會編譯:字符串不是'DateTime's,除非它們被解析爲。 –

+0

對不起。我正在轉換並添加到列表中 – balaji

回答

3

這裏是一個輔助功能,基於的是對當前和以前的項的功能組項目確定該項目應在現有組中,或一個新的組:

public static IEnumerable<IEnumerable<T>> GroupWhile<T>(
    this IEnumerable<T> source, Func<T, T, bool> predicate) 
{ 
    using (var iterator = source.GetEnumerator()) 
    { 
     if (!iterator.MoveNext()) 
      yield break; 

     List<T> list = new List<T>() { iterator.Current }; 

     T previous = iterator.Current; 

     while (iterator.MoveNext()) 
     { 
      if (predicate(previous, iterator.Current)) 
      { 
       list.Add(iterator.Current); 
      } 
      else 
      { 
       yield return list; 
       list = new List<T>() { iterator.Current }; 
      } 

      previous = iterator.Current; 
     } 
     yield return list; 
    } 
} 

現在你可以寫:

var intervals = dates.GroupWhile((prev, next) => 
     prev.Date.AddDays(1) == next.Date) 
    .Select(g => new sampleWithIntervals() 
    { 
     startDate = g.Min(s => s.Date), 
     endDate = g.Max(s => s.Date) 
    }); 
+0

我沒有收到任何列表作爲結果 – balaji

+0

@balaji在我寫的測試中工作得很好。也許你的輸入數據集是空的。 – Servy

+0

我已經在靜態類中定義了這個靜態方法。那是對的嗎? – balaji

相關問題