You can make an extension method as follows:
public static IEnumerable<DateTime> DaysUpTo(this DateTime startDate, DateTime endDate)
{
DateTime currentDate = startDate;
while (currentDate <= endDate)
{
yield return currentDate;
currentDate = currentDate.AddDays(1);
}
}
Then you can use it as follows:
DateTime Today = DateTime.Now;
DateTime NextWeek = DateTime.Now.AddDays(7);
var weekDays = Today.DaysUpTo(NextWeek).ToList();
Or with the example you used:
DateTime start = new DateTime(2010, 1, 1);
DateTime maxDate = new DateTime(2010, 1, 11);
List<DateTime> allDays = start.DaysUpTo(maxDate).ToList();
Edit:
If you really want to implement LINQ, this will work too:
DateTime start = new DateTime(2010, 1, 1);
DateTime maxDate = new DateTime(2010, 1, 11);
List<DateTime> allDays = Enumerable
.Range(0, 1 +(maxDate - start).Days)
.Select( d=> start.AddDays(d))
.ToList();
source
share