Count Occurence of Specific Day between two Dates in C#
Question:
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,...
Answer:
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))
.ToList();
Now get Count on the base of day, currently it will get Count of Monday:
var MondayCount = dates.Count(x => x.DayOfWeek == day);