我正在为ASP.NET MVC菜单编写一个类。我希望能够采取一切博客条目列表,并与此类似的存档菜单:有没有更好的解决方案这个清单<DateTime>排序?
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](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.aspx)中的'OrderBy'和'GroupBy'。后者会让你的团队(然后可以对每个组中的元素进行计数),前者将得到团队的排序。用“花哨的LINQ语法”装饰...或作为常规方法调用离开(我的首选方式)。这不是一个答案,因为我只是不会放下任何代码 - 在[LINQPad](http://linqpad.net)中玩一下并享受! – 2011-07-01 20:41:55
当我尝试的时候,我很难得到入场人数。另外,GroupBy能够按月还是不按时返回DateTime组? – quakkels
你想包括空的月份吗?即如“5/2011(0)”? – svick