我正在制定议程,我有这种方法,可以在一周的特定日期给我一个特定时期内的日期。这很好用。
现在我的问题: 我正在尝试实现一个选项来选择重复模式。
例如,每两周一次。
所以我需要一种方法来不包括不合适的日期。
例如:
// example dates
string strStart = "2014-03-17";
string strEnd = "2014-04-14";
DateTime start, end;
DateTime.TryParse(strStart, out start);
DateTime.TryParse(strEnd, out end);
// example days of week
List<DayOfWeek> dw = new List<DayOfWeek>();
dw.Add(DayOfWeek.Monday);
dw.Add(DayOfWeek.Tuesday);
Dates = GetDayofWeekDateOcurrences(start, end, dw, 2);
这给出了这个日期列表;
// result
/*
> 2014-03-17
> 2014-03-18
> 2014-03-24
> 2014-03-25
> 2014-03-31
> 2014-04-01
> 2014-04-07
> 2014-04-08
> 2014-04-14
*/
// desired dates for a two week repetition
/*
> 2014-03-17 // monday
> 2014-03-18 // tuesday
> 2014-04-07 // monday
> 2014-04-08 // tuesday
*/
方法;
private List<DateTime> GetDayofWeekDateOcurrences(DateTime start, DateTime end, List<DayOfWeek> dw, int repeatOn)
{
// repeatOn Will be for example : every 2 weeks;
int numberOfDays = end.Subtract(start).Days + 1;
var dates = Enumerable.Range(0, numberOfDays)
.Select(i => start.AddDays(i)) // (i * repeatOn) gives wrong dates
.Where(d => dw.Contains(d.DayOfWeek) && d <= end).ToList();
return dates.ToList();
}
答案 0 :(得分:2)
如果你想使用LINQ:
,这应该有效private List<DateTime> GetDayofWeekDateOcurrences(DateTime start, DateTime end, int everyNthWeek, List<DayOfWeek> dw)
{
int numberOfDays = end.Subtract(start).Days + 1;
var dates = Enumerable.Range(0, numberOfDays)
.GroupBy(i => i / 7 % everyNthWeek)
.Where(g => g.Key == 0)
.SelectMany(g => g.Select(i => start.AddDays(i))
.Where(d => dw.Contains(d.DayOfWeek)))
.ToList();
return dates;
}