8

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

有时它会引发错误,有时它没关系。我不知道怎么了。

这是我的方法:

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
4

1 回答 1

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

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

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

于 2013-01-21T06:12:31.617 回答