Reputation: 111
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
Reputation: 62213
==
, that is for equality checking. A single =
is an assignmentint 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.
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