我一直在 stackoverflow.com 和 Interwebz 上寻找如何将 Linq 与 Distinct()
一起使用,但我的情况并不顺利。
我想要做的是显示一个日期列表(2015 年 8 月、2015 年 7 月等),每个日期只显示一次。
发生的情况是月份重复,因为您可以在一个月内多次发布新博文。我认为使用 Distinct 会有所帮助,但它似乎什么也没做。当我尝试添加 GroupBy()
时,我的 OrderByDescending
停止工作,而且我还没有足够的经验将其简单地转换成 IList
,这我在其他几个例子中看到过。
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);
执行此操作的最佳方法是什么?
我试过从其他示例中提取片段,但无济于事。提前致谢。
更新:感谢您的帮助!这是工作代码,希望它能在将来帮助其他人。
代码隐藏:
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>
最佳答案
如果您的 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"
格式更改为您认为合适的任何其他格式。
关于c# - Linq 语句 distinct 不适用于日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32481429/