我目前正在考虑是否可以使用C#循环一个集合,但将集合中的项组织成组并以这种方式输出它们。
所以,我的收藏如下:
<ul class="list-unstyled">
@foreach (IPublishedContent destination in destinations.Descendants("country").OrderBy(x => x.Name))
{
<li><a href="@destination.Url">@destination.Name</a></li>
}
</ul>这输出,但在集合中有许多项作为链接。但是,如果我想将这些项目中的6个分类到它们自己的无序列表中,那么如果我的收藏中有24个条目,而不是只有一个无序列表,那么我有4个项目呢?
我使用的是Razor,所以最初我想出了以下内容(逻辑有点坏了),但这将无法在Razor中验证,因为未关闭的html标记。
int count = 0;
@foreach (IPublishedContent destination in destinations.Descendants("country").OrderBy(x => x.Name))
{
if (count == 0){ <ul class="list-unstyled">}
<li><a href="@destination.Url">@destination.Name</a></li>
@count++
if(count == 5){
count = 0;
</ul>
}
}而且,这个逻辑有根本的缺陷,因为它要求集合中有一个可划分的项目数。此外,当集合结束时,除其他问题外,您将没有一个结束标记。
有人对另一种方法有什么建议吗?我确实认为可以使用一些lamda函数来实现这一点,但是我对Linq还很陌生,所以不太确定。
如有任何建议,将不胜感激。
发布于 2015-04-09 15:07:59
您可以使用以下技术将它们分成几个组:
var list = destinations.Descendants("country").OrderBy(x => x.Name);
var groups = list
.Select((x, i) => new { Index = i, Destination = x })
.GroupBy(x => x.Index / 6)
.Select(x => x.Select(y => y.Destination));然后使用两个嵌套的foreach循环来呈现它们,即
@foreach (var group in groups)
{
<ul>
@foreach (var destination in group)
{
<li><a href="@destination.Url">@destination.Name</a></li>
}
</ul>
}https://stackoverflow.com/questions/29542037
复制相似问题