我正在为ASP.NET MVC菜单编写一个类。我希望能够获取所有博客条目的列表,并制作类似于此的存档菜单:
1/2011 (2)
3/2011 (1)
4/2011 (12)
etc...
以下是我正在使用的代码:
public class ArchiveMenuModel
{
private List<ArchiveMenuItem> menuItems;
public List<ArchiveMenuItem> MenuItems { get { return menuItems; } }
public ArchiveMenuModel(List<DateTime> dates, string streamUrl)
{
menuItems = new List<ArchiveMenuItem>();
int itemCount = 0;
dates = dates.OrderByDescending(x => x).ToList();
for (int i=0; i<dates.Count; i++)
{
itemCount++;
if(i+1 < dates.Count)
{
if(!(dates[i].Month == dates[i + 1].Month && dates[i].Year == dates[i + 1].Year))
{
menuItems.Add(new ArchiveMenuItem(streamUrl, dates[i].Month, dates[i].Year, itemCount));
itemCount = 0;
}
}
else
{
menuItems.Add(new ArchiveMenuItem(streamUrl, dates[i].Month, dates[i].Year, itemCount));
}
}
}
}
有没有更好的方法,也许是通过使用Linq或其他东西?具体来说,我不喜欢的代码部分是:
if(!(dates[i].Month == dates[i + 1].Month && dates[i].Year == dates[i + 1].Year))
如果我可以避免这种丑陋的if语句,那就太棒了!
答案 0 :(得分:2)
menuItems = dates
.GroupBy(x => new DateTime(x.Year, x.Month, 1))
.Select(x=> new{Date = x.Key, Count = x.Count()})
.OrderByDescending(x => x.Date)
.Select(x => new ArchiveMenuItem(streamUrl,
x.Date.Month,
x.Date.Year,
x.Count))
.ToList();
答案 1 :(得分:1)
var menuItems = from date in dates
group date by new { date.Year, date.Month } into g
select new { g.Key.Year, g.Key.Month, Count = g.Count() } into month
orderby month.Year, month.Month
select new ArchiveMenuItem(streamUrl, month.Month, month.Year, month.Count);
此LINQ查询
ArchiveMenuItem
答案 2 :(得分:0)
var memuItems = dates.Select(o => o.Date.AddDays(-o.Date.Day + 1))
.GroupBy(o => o, (o, p) => new {MonthAndYear = o.Date, EntriesCount = p.Count()})
.Select(o => new ArchiveMenuItem(streamUrl, o.MonthAndYear.Month, o.MonthAndYear.Year, o.EntriesCount));
我减去日期(到本月的第一天),所以我可以使用年份和月份进行分组。
答案 3 :(得分:0)
@svick和@danyolgiax,
这是我从dany的链接中得出的结果:
public class ArchiveMenuModel
{
private List<ArchiveMenuItem> menuItems;
public List<ArchiveMenuItem> MenuItems { get { return menuItems; } }
public ArchiveMenuModel(List<DateTime> dates, string streamUrl)
{
menuItems = new List<ArchiveMenuItem>();
dates = dates.OrderByDescending(x => x).ToList();
var grouped = from d in dates
group d by new { month = d.Month, year= d.Year } into d
select new { dt = d, count = d.Count() };
foreach(var item in grouped)
{
menuItems.Add(new ArchiveMenuItem(streamUrl, item.dt.Key.month, item.dt.Key.year, item.count));
}
}
}
答案 4 :(得分:-1)
这些方面应该有效:
menuItems.GroupBy(x => x.Month + "/" + x.Year);
我不知道包含DateTime的属性的名称,但它必须设置为,
menuItems.GroupBy(x => x.(datetime).Month + "/" + x.(datetime).Year);