获取特定时期的所有帖子(lambda表达式)

时间:2012-01-31 18:32:11

标签: asp.net lambda

我想要一个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...?
}

3 个答案:

答案 0 :(得分:2)

描述

您可以使用DateTime过滤器中的Year属性MonthWhere来执行此操作。

示例

return m_PostRepository.GetPosts().Where(x => x.PublishDate.Year == 2011 &&
                                              x.PublishDate.Month == 10).ToList();

更多信息

Bronzato发表评论后更新

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]))}