简体   繁体   中英

Sequence contains no matching element error in Linq Statement

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM