2013-05-29 78 views
3

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

日历最初将包含指定范围内的所有日期,例如2013年1月31日 - 2015年1月31日。我想过滤此列表以仅包含与日历中的第一天数字匹配的日期,例如if第一天的日历是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我的要求是这样,这是在返回时:

  • 31月2013
  • 2013年2月28日
  • 年04月30 5月2013

...等

什么是实现这一目标的最佳方式是什么?星期三的早晨我的大脑啄食!

我想,如果在所有可能的答案是一个完美的一个班轮LINQ声明:)

非常感谢,

亚历

+0

你能提供将被使用的年份吗? –

+0

所以你不是真的想要那天的日子是'31',而是每个月的最后一天?也许这种方法将有助于:'bool IsLastOfMonth(DateTime date){return date == new DateTime(date.Year,date.Month,1).AddMonths(1).AddDays(-1); }'(未测试) – Corak

+0

预过滤的日历很可能包含一个3 - 5年的日期范围,比如说2012 - 2015年,所有日期介于两者之间。这是否回答你的问题? – Huntsman

回答

1

DateTime.DaysInMonth来救援!

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

不错的一个 - 我认为这会做的伎俩! – Huntsman

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

他得到一天,然后他要么得到那个数字的一​​天,要么在这个月的最后一天太大。几乎在那里,但不完全。 -1。 –

+0

起初误解了这个问题.. –

+0

Downvote恢复:) –