Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Find the count of a weekday between two dates without iterating/looping

2.71/5 (4 votes)
11 Nov 2011CPOL 21.9K  
Single line in Linq This gets you the number of weekdays, i.e., Monday to Friday between given two dates.[VB]Dim dt1 As New Date(2011, 1, 1)Dim dt2 As New Date(2011, 1, 15)Dim days As Integer = (From d As Date In _ (Enumerable.Range(0, 1 +...
Single line in Linq

This gets you the number of weekdays, i.e., Monday to Friday between given two dates.
[VB]
VB
Dim dt1 As New Date(2011, 1, 1)
Dim dt2 As New Date(2011, 1, 15)
Dim days As Integer = (From d As Date In _
  (Enumerable.Range(0, 1 + dt2.Subtract(dt1).Days).Select(Function(offset) dt1.AddDays(offset)).ToArray()) _
  Where d.DayOfWeek >= DayOfWeek.Monday And d.DayOfWeek <= DayOfWeek.Friday Select 1).Sum

[C#]
C#
DateTime dt1 = new DateTime(2011, 1, 1);
DateTime dt2 = new DateTime(2011, 1, 15);
int days = (from d in (Enumerable.Range(0, 1 + dt2.Subtract(dt1).Days).Select(offset => dt1.AddDays(offset)).ToArray())where d.DayOfWeek >= DayOfWeek.Monday & d.DayOfWeek <= DayOfWeek.Friday1).Sum;


You can easily modify it to get the count of a particular day as,
[VB]
VB
Dim dt1 As New Date(2011, 1, 1)
Dim dt2 As New Date(2011, 1, 15)
Dim days As Integer = (From d As Date In _
  (Enumerable.Range(0, 1 + dt2.Subtract(dt1).Days).Select(Function(offset) dt1.AddDays(offset)).ToArray()) _
  Where d.DayOfWeek = DayOfWeek.Monday Select 1).Sum

[C#]
C#
DateTime dt1 = new DateTime(2011, 1, 1);
DateTime dt2 = new DateTime(2011, 1, 15);
int days = (from d in (Enumerable.Range(0, 1 + dt2.Subtract(dt1).Days).Select(offset => dt1.AddDays(offset)).ToArray())where d.DayOfWeek == DayOfWeek.Monday).Sum;


See here, Enumerable.Range gets you the array of dates between given dates. You can apply your conditions and get different results using Linq on it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)