Introduction
Without going into a deep discussion of whether code or compiler is looping or not, it should be noted that LINQ can be very useful for tasks like this.
Further, if you add the methods using extension of DateTime
, much flexibility is gained. This alternative demonstrates first how a range of weekdays can be created - offering you a collection of the actual dates - then, how to count the elements of the range which is the original goal of the tip.
Both methods are implemented with very little code which is easy to comprehend, maintain, and expand.
Using the Code
The code separates creation of the range of weekdays and the counting of these.
Using extensions allows for very tight code:
DateTime currentDate = DateTime.Today;
DateTime anotherDate = currentDate.AddDays(23);
DayOfWeek thursday = DayOfWeek.Thursday;
Console.WriteLine(currentDate.WeekdayCount(anotherDate, thursday));
Console.ReadKey();
Code
using System;
using System.Collections.Generic;
using System.Linq;
namespace DateTimeExtension
{
public static class DateTimeExtensionMethods
{
public static IEnumerable<DateTime> Weekdays(this DateTime currentDate,
DateTime anotherDate, DayOfWeek dayOfWeek)
{
int sign = anotherDate.CompareTo(currentDate);
return Enumerable.Range(0, sign * anotherDate.Subtract(currentDate).Days)
.Select(delta => currentDate.AddDays(sign * (1 + delta)))
.Where(date => date.DayOfWeek == dayOfWeek);
}
public static int WeekdayCount(this DateTime currentDate,
DateTime anotherDate, DayOfWeek dayOfWeek)
{
return currentDate.Weekdays(anotherDate, dayOfWeek).Count();
}
}
}
Usage is included as an in-line brief description.
History
- 6th April, 2012: Initial version
Microsoft MVP, Most Valuable Professional, since 2017.
It started with BASIC in the 80s, then moved to PDC Prolog, and then - when Access 1.0 was launched - "back to Basic", or rather Access Basic. Then followed VBA (Visual Basic for Applications) starting with Microsoft Access 95/97 and still going with Access 2019/365.
Still I do some VBA, but since 2008 my main focus has been C#.
Application area is mainly accounting and custom applications related to accounting.