序列在Linq语句中不包含匹配元素错误

时间:2013-01-21 06:06:53

标签: c# .net linq

我正在尝试调试我的方法,但我不知道它有什么问题。

有时它会抛出错误,有时它也没关系。我不知道出了什么问题。

这是我的方法:

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);
                }
    }

这是出现错误的行:

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();

这是错误:

 InvalidOperationException : Sequence contains no matching element

1 个答案:

答案 0 :(得分:13)

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();

尝试使用FirstOrDefaultLastOrDefault代替FirstLast,如果没有与lambda匹配的元素,这些方法将返回调用它们的类型的默认值您提供的表达式作为参数。

如果是g.FirstOrDefault(),如果g为空,则返回默认值;如果是g.LastOrDefault(d => d.DayOfWeek != DayOfWeek.Saturday && d.DayOfWeek != DayOfWeek.Sunday),则返回默认值,如果所有天数是星期六或星期日,则返回默认值。