【发布时间】:2011-07-01 20:37:59
【问题描述】:
我正在为 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 语句,那就太好了!
【问题讨论】:
-
里面有 LINQ 吗? ;-) 参见IEnumerable 中的
OrderBy和GroupBy。后者将获得您的组(然后可以计算每个组中的元素),前者将获得有序的组。用“花哨的 LINQ 语法”装饰......或保留正常的方法调用(我的首选方式)。这不是一个答案,因为我只是不想写下任何代码——在LINQPad 玩一会儿,享受吧! -
当我尝试这样做时,我无法获得条目计数。另外,
GroupBy是否能够按月+年而不是时间返回DateTime组? -
是否要包括空月份? IE。像“5/2011 (0)”这样的行?
-
@svick - 我在想我不会包括空月。找不到充分的理由……至少现在还没有;-)
标签: c# asp.net-mvc linq sorting