1

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);
 }
Vignesh Murugan
  • 575
  • 5
  • 18

2 Answers2

8

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();
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

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.

Community
  • 1
  • 1
Henry Wilson
  • 3,281
  • 4
  • 31
  • 46