2012-02-01 56 views
24

可能重複:
How do I loop through a date range?的foreach日在一個月

有沒有一種方法,使每一天的foreach循環在特定月份?

的東西

思維像

foreach (DateTime date in DateTime.DaysInMonth(2012, 1)) 
{ 
} 
+0

你需要與每一天?你每天需要一個完整的日期還是數值? – sll 2012-02-01 14:04:18

+3

實際上,如果DateTime在請求的日期範圍內確實返回IEnumerable ,我認爲它會很棒。 – adelphus 2012-02-01 14:08:22

+0

@sll我正在做一個日曆,全年可見,在那裏人們將能夠使單獨的約會 – 2012-02-01 16:30:01

回答

55

你可以寫很容易地一個輔助方法:

public static IEnumerable<DateTime> AllDatesInMonth(int year, int month) 
{ 
    int days = DateTime.DaysInMonth(year, month); 
    for (int day = 1; day <= days; day++) 
    { 
     yield return new DateTime(year, month, day); 
    } 
} 

然後調用它:

foreach (DateTime date in AllDatesInMonth(2012, 1)) 

這可能是som的矯枉過正ething你只是做一次,但它是比使用for環或類似的東西,如果你這樣做了很多更好。它使你的代碼說只是你想要什麼來實現的,而不是力學你怎麼做。

+1

更妙的是替換該功能與前兩行:的foreach(VAR天Enumerable.Range(1,DateTime.DaysInMonth(年,月)) – DamienG 2012-02-01 16:18:33

+0

我覺得這個問題剛剛Skeeted超過 – Joe 2015-03-17 23:59:13

20

嘗試使用一個for循環來代替。

for (int i = 1; i <= DateTime.DaysInMonth(year, month); i++) 
{ 
    DateTime dt = new DateTime(year, month, i); 
} 
10

你可以用一個簡單的循環做到這一點:

DateTime first = new DateTime(2012, 1, 1); 
for (DateTime current = first ; current.Month == first.Month ; current = current.AddDays(1)) { 
} 
+0

我喜歡利用經常被忽視的能力,用來與比INT其它數據類型的循環筆記。 – 2012-03-07 21:51:44

13

您可以使用範圍:

Enumerable 
    .Range(1, DateTime.DayInMonth(2012, 1) 
    .Select(i => new DateTime(2012, 1, i))) 
    .ToList() // ForEach is not a Linq to Sql method (thanks @Markus Jarderot) 
    .ForEach(day => Console.Write(day)); 
+3

或者一步' Enumerable.Range(1,DateTime.DayInMonth(2012,1)),選擇(天=>新的日期時間(2012年,1天))' – Ray 2012-02-01 14:07:02

+0

@Ray,謝謝!好主意 – Joe 2012-02-01 14:12:05

+0

我喜歡這樣的回答最多。 – NibblyPig 2012-02-01 16:12:41

5

這是相當容易產生天的枚舉。這裏有一種方法可以做到這一點

Enumerable.Range(1, DateTime.DaysInMonth(year, month)).Select(day => 
    new DateTime(year, month, day))