我已经找到了一种为每个月创建文件的方法。
像这样:
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 :(得分: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
,因为这会改变其意图。我其实更喜欢其他答案。
答案 1 :(得分:2)
将linq添加到方法的结果
foreach (DateTime weekDay in AllDatesInMonth(...).Where(d=>d.DayOfWeek!= DayOfWeek.Saturday && d.DayOfWeek!=DayOfWEek.Sunday)){
...
}
这种方式如果您需要在所包含的日期(节假日?)上施加更多条件,那么您可以添加另一个.Where
答案 2 :(得分: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;
}
}