2016-07-07 72 views
0

我必須實現一個接收DateTime列表的算法,它恢復每個月的最新DateTime,我不知道該怎麼做。 例子:如何選擇每月的最新日期時間?

29/06/2016 -> Lastest date of june 
27/06/2016 
05/05/2016 -> Lastest date of may 
15/04/2016 -> Lastest date of april 
13/04/2016 
... 

預期結果

29/06/2016 
05/05/2016 
15/04/2016 
+0

我會計算每個月有多少天了,然後檢查每月這是最新的日期。 – user743414

+1

按年/月分組日期時間,並從每個組中選擇最大值 – Philippe

回答

4

你說的是從日期列表中每月的最大日期。您可以通過使用GroupByMax,如獲得與LINQ:

var maxDatesPerMonth=from date in dates 
         group date by new {date.Year,date.Month} into months 
         select months.Max(); 

var maxDatesPerMonth=dates.GroupBy(date=>new {date.Year,date.Month}) 
          .Select(months=>months.Max()); 
0

嘗試......

class Program 
{ 
    static void Main(string[] args) 
    { 
     var dateTimes = new[] 
     { 

      new DateTime(2016, 06, 29), 
      new DateTime(2016, 06, 27), 
      new DateTime(2016, 05, 05), 
      new DateTime(2016, 04, 15), 
      new DateTime(2016, 04, 13) 
     }; 

     var years = dateTimes.GroupBy(x => x.Year).OrderByDescending(x => x.Key); 

     foreach (IGrouping<int, DateTime> grouping in years) 
     { 
      var months = grouping.GroupBy(x => x.Month); 

      foreach (IGrouping<int, DateTime> month in months) 
      { 
       Console.WriteLine(month.First()); 
      } 
     } 

     Console.ReadLine(); 
    } 
} 

此輸出以下...

29/06/2016 00:00:00 
05/05/2016 00:00:00 
15/04/2016 00:00:00 
+0

它有點粗糙 - 沒有時間優化它,但它應該工作。一旦你明白了,你可以在你認爲合適的時候簡化它。 – Jay

+0

爲什麼'首先'而不是'最大'?????? –

+0

它已經被group-by聲明命令 - 我只需要挑出第一個,因爲它與MAX完全相同。正如我上面所說 - 這工作,但沒有優化。請解釋爲什麼你的代碼有問題? – Jay

0

你可以解決這個問題LINQ。

僞代碼:

dateList.Where(x => x.Month == 6).Max() 

這給你六月的最後日期。

確保使用DateTime類型的正確屬性而不是*.Month。您可能還需要指定.Max(),可能是.Select(x => x.Day).Max()

儘管如此:LINQ是要走的路。 希望它有幫助。

+0

這不會返回日期的月末,它會返回一個月的最大日期。你應該使用GroupBy –