假设我有一个数据库,里面有过去两年的大约5000篇博客文章,我正在尝试创建“每月”存档,这样我就可以以一种更符合逻辑的方式显示数据。
出于某种原因,我从来没有真正使用过那么多的date,而且我的知识也很匮乏。
我正在使用Linq/C#;有人能给我指出正确的方向来学习如何做到这一点吗?
干杯
哑光
发布于 2010-12-30 16:50:29
嗯,它与基于整数属性的过滤没有太大区别:
DateTime beginDate, endDate;
// set beginDate and endDate as appropriate, based on the month you are displaying
// beginDate = new DateTime(2011, 1, 1);
// endDate = beginDate.AddMonths(1);
var query = from post in db.Entries
where post.Date >= beginDate && post.Date < endDate
orderby post.Date descending
select post;发布于 2010-12-30 17:09:14
这真的取决于你的需求和UI的流程。在大多数情况下,您可以提供一个日期范围,并查询该范围内的帖子。
格式化生成的帖子完全取决于你,你必须使用什么工具,以及你需要它做什么。但是,您可以使用GroupBy对某个日期下的帖子进行分组,然后遍历每个组以输出单独的链接。下面的示例在控制台应用程序中向您展示了这一点。您应该能够推断如何将其应用于您的需求。
var postsByMonth = (from post in context.Posts
where post.Date >= start && post.Date < end
orderby post.Date descending
select post).GroupBy(post => new DateTime(post.Date.Year, post.Date.Month, 1));
foreach (IGrouping<DateTime, Post> posts in postsByMonth)
{
Console.WriteLine("{0:MMM} {0:yyyy}", posts.Key);
Console.WriteLine("======================");
Console.WriteLine();
foreach (Post post in posts)
{
Console.WriteLine("Post from {0}", post.Date);
}
Console.WriteLine();
}https://stackoverflow.com/questions/4561203
复制相似问题