我想要一个lambda表达式来获取我在特定月/年范围内使用PublishDate的所有帖子(例如10/2011)。
public IEnumerable<Post> SearchPosts(string periode)
{
// periode may be 10/2011 so I would like all posts from 10/01/2011 to 10/31/2011
return m_PostRepository.GetPosts().Where(x => x.PublishDate...?
}
答案 0 :(得分:2)
您可以使用DateTime
过滤器中的Year
属性Month
和Where
来执行此操作。
return m_PostRepository.GetPosts().Where(x => x.PublishDate.Year == 2011 &&
x.PublishDate.Month == 10).ToList();
DateTime? date;
// does date has a value ? If yes, apply the filter. If not return everything.
if (date.HasValue)
{
return m_PostRepository.GetPosts().Where(x => x.PublishDate.Year == date.Value.Year &&
x.PublishDate.Month == date.Value.Month).ToList();
} else return return m_PostRepository.GetPosts();
答案 1 :(得分:1)
您也可以这样尝试(使用PublishDate
作为Nullable<DateTime>
):
DateTime date;
if (DateTime.TryParseExact(value, "MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
var result = m_PostRepository.GetPosts().Where(x => x.PublishDate.HasValue &&
x.PublishDate.Value.Month == date.Month &&
x.PublishDate.Value.Year == date.Year).ToList();
}
答案 2 :(得分:0)
public IEnumerable<Post> SearchPosts(string periode){
string[] _periode = periode.Split("/");
return m_PostRepository.GetPosts().Where(x => x.PublishDate.year = convert.ToInt16(_periode[1])).Where(x => x.PublishDate.Month= convert.ToInt16(_periode[0]))}