2013-05-29 74 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恢復:) –