1

我有这个代码,它失败了,因为 thisMonthSundays 是空的:

 public ActionResult TradeUKKPISearchesData() //show dropdownlist in the view
{
    var now = DateTime.Now;
    var lastMonth = now.AddMonths(-1);
    var thisMonthSundays = GetDatesOfSundays(now.Year, now.Month).OrderByDescending(x => x.Date);
    var lastMonthSundays = GetDatesOfSundays(lastMonth.Year, lastMonth.Month).OrderByDescending(x => x.Date); //problem here, must add some sort of check here?
    var sundaysToTakeFromLastMonth = 4;
    var sundays = thisMonthSundays.Concat(lastMonthSundays.Skip(Math.Max(0, lastMonthSundays.Count() - sundaysToTakeFromLastMonth)).Take(sundaysToTakeFromLastMonth));

    var allSundaysInThisMonth = new SundaysInMonthViewModel
    {
        AllSundays = sundays.Select(x => new SelectListItem
        {
            Value = x.ToString("dd/MM/yyyy"),
            Text = x.ToString("dd/MM/yyyy"),
        })
    };

    var selectedSunday = new SundaysInMonthViewModel
    {
        SelectedSunday = thisMonthSundays.Where(x => x <= now).Last() //failed here
    };

  return View(allSundaysInThisMonth);
}

private IEnumerable<DateTime> GetDatesOfSundays(int year, int month)
{
  var ci = CultureInfo.InvariantCulture;
  for (int i=1; i <= ci.Calendar.GetDaysInMonth(year, month); i++)
  {
      var date = new DateTime(year, month, i);
      if ((date.DayOfWeek == DayOfWeek.Sunday) && (date <= DateTime.Now))
      {
          yield return date; //skips all for this month
      }
  }
}

我需要解决这个问题,请帮助您的想法?谢谢

4

2 回答 2

3

由于 Octobar 月份到目前为止还没有星期天,因此变量SelectedSunday为空....

您可以LastOrDefault()改用:

SelectedSunday = thisMonthSundays.Where(x => x <= now).LastOrDefault() ;

DateTime注意:类型的默认值DateTime.Min1/1/0001 12:00:00 AM

于 2012-10-01T10:45:27.150 回答
1

您的代码中存在一些错误。

  1. 使用var不是你想在任何地方都做的事情。
  2. 你永远不应该在你的函数中使用任意值。您应该在函数中添加一个限制参数并传递调用,而不是检查日期是否早于今天DateTime.Now
  3. 您的函数已经返回今天之前给定月份的所有星期日。您的 Linq 请求只是代码的复制,每次都会返回整个集合。
  4. 由于今天是 10-01 并且我们是星期一,因此在今天之前的 10 月没有星期日。这就是您的收藏为空的原因。
于 2012-10-01T10:58:59.557 回答