Jalpesh p. Vadgama made an blog post for C# beginners to find Saturday, Sunday from a date range using a simple for loop and switch statements. I had a similar requirement where the implementation is more reusable that I like to share now. The code sample makes use of C# features such as extension methods, LINQ, the yield statement, and the params keyword.
Within Jalpesh’s code a for loop iterates through a date range by using the time span between the dates and a for loop to iterate until the number of dates is reached. Using the DayOfWeek property of the DateTime type the weekday was accessed, and with a switch statement.
Here is the new version. I’m creating an extension method to the DateTime type, so the method WeekdaysFromDateRange can be used directly with the DateTime type. fromDate and toDate are the first parameters on the method. The last parameter is an DayOfWeek array that with the params keyword allows passing any number of DayOfWeek values. Within the implementation of the method a while loop iterates through all dates up to the end date and checks by using the Contains extension method defined in the System.Linq namespace if the weekday is one of the required ones and if it is returns it with the yield return statement.
1 public static class DateTimeExtension 2 { 3 public static IEnumerable<DateTime> WeekdaysFromDateRange( 4 this DateTime fromDate, DateTime toDate, params DayOfWeek[] dayOfWeek) 5 { 6 DateTime date = fromDate; 7 while (date <= toDate) 8 { 9 if (dayOfWeek.Contains(date.DayOfWeek)) 10 yield return date; 11 date = date.AddDays(1); 12 } 13 } 14 }
This new method can now be used like a method from the DateTime types, passing an end date and any number of weekdays. In the sample code I’m passing DayOfWeek.Saturday and DayOfWeek.Sunday so that all Saturdays and Sundays are displayed within the foreach loop.
.
1 DateTime beginDate = new DateTime(2011, 3, 1); 2 DateTime endDate = new DateTime(2011, 6, 4); 3 foreach (var date in beginDate.WeekdaysFromDateRange( 4 endDate, DayOfWeek.Saturday, DayOfWeek.Sunday)) 5 { 6 Console.WriteLine("{0:D}", date); 7 }
Running the application the resulting dates are shown with the long date format.
More information on C# language features in my book Professional C# 4 and .NET 4 and in my C# Workshops.
Christian
CN innovation
Comments