Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequence contains no matching element error in Linq Statement

Tags:

c#

.net

linq

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
like image 423
jomsk1e Avatar asked Jan 21 '13 06:01

jomsk1e


1 Answers

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.

like image 60
TKharaishvili Avatar answered Nov 06 '22 00:11

TKharaishvili