I am trying to debug my method but I don't know what's wrong with it.
There are times that it throws an error and sometime it's okay. I don't know what's wrong.
Here's my method:
private void GetWorkingWeek(int month, int year)
{
var cal = System.Globalization.CultureInfo.CurrentCulture.Calendar;
var daysInMonth = Enumerable.Range(1, cal.GetDaysInMonth(year, month));
var listOfWorkWeeks = daysInMonth
.Select(day => new DateTime(year, month, day))
.GroupBy(d => cal.GetWeekOfYear(d, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday))
.Select(g => Tuple.Create(g.Key, g.First(), g.Last(d => d.DayOfWeek != DayOfWeek.Saturday && d.DayOfWeek != DayOfWeek.Sunday)))
.ToList();
foreach (var weekGroup in listOfWorkWeeks)
{
Console.WriteLine("Week{0} = {1} {2} to {1} {3}"
, weekNum++
, System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(month)
, weekGroup.Item2.Day
, weekGroup.Item3.Day);
}
}
This is the line where the error appear:
var listOfWorkWeeks = daysInMonth
.Select(day => new DateTime(year, month, day))
.GroupBy(d => cal.GetWeekOfYear(d, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday))
.Select(g => Tuple.Create(g.Key, g.First(), g.Last(d => d.DayOfWeek != DayOfWeek.Saturday && d.DayOfWeek != DayOfWeek.Sunday)))
.ToList();
This is the error:
InvalidOperationException : Sequence contains no matching element
var listOfWorkWeeks = daysInMonth
.Select(day => new DateTime(year, month, day))
.GroupBy(d => cal.GetWeekOfYear(d, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday))
.Select(g => Tuple.Create(g.Key, g.FirstOrDefault(), g.LastOrDefault(d => d.DayOfWeek != DayOfWeek.Saturday && d.DayOfWeek != DayOfWeek.Sunday)))
.ToList();
Try using FirstOrDefault
and LastOrDefault
instead of First
and Last
, these methods will return the default value of the type they are invoked for if no elements match the lambda expression you provide as a parameter.
In case of g.FirstOrDefault()
, the default value will be returned if g is empty and in case of g.LastOrDefault(d => d.DayOfWeek != DayOfWeek.Saturday && d.DayOfWeek != DayOfWeek.Sunday)
the default value will be returned if all days are either saturday or sunday.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With