Is there any helper methods to generate Dates in C#?
For example I have a Grid which shows Date,Day of all dates between given two dates.. If i select 1/1/2013 to 2/5/2013...It should Generate all dates between these two...
I tried While Loop as follows
while (startdate <= enddate)
{
var calendarDate = CreateDate();
calendarDate.CalendarDate = startdate.Date;
if (calendarDate.DayofWeek == DayOfWeekValues.Sunday.Value)
{
calendarDate.IsHoliday = true;
}
startdate = startdate.AddDays(1.0);
}
It's not clear what's wrong with your loop, it looks as if you just have to add the dates to a collection like a List<DateTime>
. However, you could also use LINQ:
int days = (enddate - startdate).Days + 1;
List<DateTime> dateRange = Enumerable.Range(0, days)
.Select(i => startdate.AddDays(i))
.ToList();
Edit : since you don't use a DateTime
but a custom class:
I don't know the class and methods involved, however, this should help to implement the same logic as you in your loop(presuming HolidayCalendarDetail
is the class):
List<HolidayCalendarDetail> dates = Enumerable.Range(0, days)
.Select(i =>
{
var calendarDate = e.CreateHolidayCalendarDetail();
calendarDate.CalendarDate = startdate.AddDays(i);
calendarDate.IsHoliday = calendarDate.CalendarDate.DayOfWeek == JobScheduleDayOfWeekValues.Sunday.Value;
return calendarDate;
}).ToList();
This has already been covered over here: Exploding a range of dates with LINQ
I don't think there is a built in .Net helper but you can certainly achieve it with LINQ or a while loop.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.