按日期过滤日期列表

时间:2013-05-29 09:39:08

标签: c# linq datetime calendar

我正在尝试按天数过滤日历(日期列表),但是在特定情况下苦苦挣扎!

日历最初将包含指定范围内的所有日期,例如2013年1月31日至2015年1月31日。我想过滤此列表以仅包含与日历中第一天编号匹配的日期,例如,如果日历中的第一天是25,返回的新过滤日历将是:

  • 2013年2月25日
  • 2013年3月25日
  • 2013年4月25日

...等

第一个例子对LINQ

来说很简单
var calendar = ...code to get calendar from DB.

//Get Day Number of First Entry in Calendar (31st for example)
int day = calendar.Dates.Select(d => d.Date.Day).First();

//Filter the rest of the calendar by this date.
return new Calendar
{
    Dates = calendar.Dates.Where(c => c.Date.Day == day).ToList()
};

我在传入31时遇到了困难。我的要求是这样返回:

  • 2013年1月31日
  • 2013年2月28日
  • 2013年4月30日
  • 2013年5月31日

...等

实现这一目标的最佳方法是什么?它在周三早上啄我的大脑!

我想尽可能的答案是一个完美的单行LINQ语句:)

非常感谢,

亚历

2 个答案:

答案 0 :(得分:1)

Dates = calendar.Dates.Where(c => c.Date.Day == Math.Min(day, DateTime.DaysInMonth(c.Year, c.Month))).ToList()

答案 1 :(得分:1)

DateTime.DaysInMonth救援!

return new Calendar
{
Dates = calendar.Dates.Where(c => c.Date.Day == Math.Min(day, DateTime.DaysInMonth(c.Year, c.Month))).ToList()
};
相关问题