Count Occurence of Specific Day between two Dates in C#

Friday, August 15, 2014 0 Comments A+ a-


I want to count occurrences, for each day of the week, between two given dates.
For example:
Between 20/07/2014 to 27/7/2014, an 8 day span, there were:
Sunday=2, monday=1, tuesday=1,...


DateTime StartDate = DateTime.Now.AddDays(-14);
DateTime EndDate = DateTime.Now;
DayOfWeek day = DayOfWeek.Monday;

First get the all days between two dates:

List<DateTime> dates = Enumerable.Range(0, (int)((EndDate - StartDate).TotalDays) + 1)
                      .Select(n => StartDate.AddDays(n))

Now get Count on the base of day, currently it will get Count of Monday:

var MondayCount = dates.Count(x => x.DayOfWeek == day);



Coursera - Hundreds of Specializations and courses in business, computer science, data science, and more