I want to do it using LINQ to Object
List<DateTime> allDays = new List<DateTime>();
DateTime start = 开发者_JAVA技巧new DateTime(2010, 1, 1);
DateTime maxDate = new DateTime(2010, 1, 11);
do
{
allDays.Add(start);
start = start.AddDays(1);
}
while (maxDate.Date >= start);
Thank you.
You could do an extension method like this:
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 like this:
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 your really want a LINQ implementation this would 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();
精彩评论