2013-04-12 24 views
0

我已經找到了一種在每月的每一天創建文件的方法。沒有周末的月中的天數爲xml文件

像這樣:

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 day in AllDatesInMonth(DateTime.Now.Year, DateTime.Now.Month)) 
{ 
    //Blablabla 
} 

這些文件被命名爲喜歡1.XML,2.XML,...

現在我要知道的是要做同樣的事情,但週末沒有文件(週六和週日)。

+0

我編輯了您的標題。請參閱:「[應該在其標題中包含」標籤「](http://meta.stackexchange.com/questions/19190/)」,其中的共識是「不,他們不應該」。 –

回答

2

一個LINQ添加到您的方法的結果

foreach (DateTime weekDay in AllDatesInMonth(...).Where(d=>d.DayOfWeek!= DayOfWeek.Saturday && d.DayOfWeek!=DayOfWEek.Sunday)){ 

... 
} 

如果需要徵收包括(節假日?)的日子多個條件這樣,那麼你可以添加另一個。凡

2

取代:

yield return new DateTime(year, month, day); 

有:

DateTime dt = new DateTime(year, month, day); 
if(dt.DayOfWeek != DayOfWeek.Saturday && dt.DayOfWeek != DayOfWeek.Sunday) 
    yield return dt; 

當然,該方法將不得不重新命名爲AllWeekDaysInMonth,因爲這改變其意圖。我其實更喜歡其他答案。

+0

這將導致DRY溢出 - 您必須在每次需要執行其他操作時修改該函數? –

+0

@StenPetrov因爲這個,我其實更喜歡其他答案。 –

0

可以使用相同的代碼,只需添加一個星期幾到Where循環的檢查:

public static IEnumerable<DateTime> AllDatesInMonth(int year, int month) 
     { 
     int days = DateTime.DaysInMonth(year, month); 

     for (int day = 1; day <= days; day++) 
     { 
      var dateToTest = new DateTime(year, month, day); 
      if (dateToTest.DayOfWeek == DayOfWeek.Saturday || dateToTest.DayOfWeek == DayOfWeek.Sunday) continue; 
      yield return dateToTest; 
     } 
    } 
相關問題