Linq声明明显不适用于日期

时间:2015-09-09 13:51:35

标签: c# linq

我一直在遍历stackoverflow.com和Interwebz,了解如何将Linq与Distinct()一起使用,但我对我的情况没有任何好运。

我要做的是显示日期列表(2015年8月,2015年7月等),每个日期只显示一次。

由于您可以在一个月内多次发布新博客帖子,因此会重复这些月份。我认为使用Distinct会有所帮助,但似乎它没有做任何事情。当我尝试添加GroupBy()时,我的OrderByDescending停止工作,而且我没有经验丰富,只需将其变成IList,我在其他几个例子中看到过。< / p>

BlogRepeater.DataSource = _PostRepository.GetAll(ConfigurationManager.GetSiteID())
    .Where(x => x.DatePublished != null && x.DatePublished >= DateTime.Now.AddYears(-1))
    .Distinct().OrderByDescending(x => x.DatePublished)
    .Select(x => x.DatePublished.Value.Date);

这样做的最佳方式是什么?

我尝试过从其他例子中获取作品,但无济于事。提前谢谢。

enter image description here

更新:感谢您的帮助!这是工作代码,希望它可以在将来帮助其他人。

代码背后:

BlogRepeater.DataSource = 
            _PostRepository
            .GetAll(ConfigurationManager.GetSiteID())
            .Where(x => x.DatePublished != null && x.DatePublished >= DateTime.Now.AddYears(-1) && x.Status == "Published")
            .Select(x => x.DatePublished.Value.ToString("MMM yyyy"))
            .Distinct()
            .OrderBy(x => x);
        BlogRepeater.DataBind();

前端:

<a href="/Blog/Archive/<%#(Container.DataItem)%>"><%#(Container.DataItem)%></a>

1 个答案:

答案 0 :(得分:6)

如果您的DatePublished字段包含不同时间的DateTime值,则.Distinct()将无法按预期运行,因为这些值本质上是不同的。

如果您需要不同的日期,而不是日期/时间,那么您可以在.Select之前移动最后.Distinct()

BlogRepeater.DataSource = 
  _PostRepository
    .GetAll(ConfigurationManager.GetSiteID())
    .Where(x => x.DatePublished != null && x.DatePublished >= DateTime.Now.AddYears(-1))
    .Select(x => x.DatePublished.Value.Date)   
    .Distinct()
    .OrderByDescending(x => x);

如果您想查找不同的月份,而不是日期,则必须更改

.Select(x => x.DatePublished.Value.Date)

行到

.Select(x => x.DatePublished.Value.ToString("MMM yyyy"))

随意将"MMM yyyy"格式更改为您认为合适的其他格式。