Sergio Marquez
Sergio Marquez

Reputation: 111

How to get the number of dates of a specific Day Of the week in a List<DateTime>?

Good day, I have a list, with some dates, I need to get The number of days of a day of the week, for example, get in a int variable the number of dates that are on Sunday, another int for Monday...

I've tried using the following code:

List<int> SundayDates = DateList.FindAll(x => x.DayOfWeek = DayOfWeek.Sunday) 

but it says that it's read only, (And DateList, is the list where I storage my dates and where I want to get it).

Upvotes: 2

Views: 118

Answers (1)

Igor
Igor

Reputation: 62213

  • You need to use ==, that is for equality checking. A single = is an assignment
  • To count the number of occurrences use Count.
int numberOfSundays = DateList.Count(x => x.DayOfWeek == DayOfWeek.Sunday);

Here is a count for each day of the week. The grouped join ensures that even if a day is not present in the list (example no occurrences of Monday) that it will still occur in the resulting list with a count of 0.

dotnetfiddle

var DateList = new List<DateTime>(); // your populated list of dates

var allDaysOfWeek = Enum.GetValues(typeof(DayOfWeek)).Cast<DayOfWeek>();
var totalDayCounts = allDaysOfWeek.GroupJoin(DateList, dayOfWeek => dayOfWeek, date => date.DayOfWeek, (dayOfWeek, times) => new
{
    DayOfTheWeek = dayOfWeek,
    DayOfWeekCount = times.Count()
});

do not forget to add using System.Linq; at the top of your code file

Upvotes: 6

Related Questions