Skip to main content
 首页 » 编程设计

c#之分组输出集合中的项目

2024年08月06日40飞鱼

我目前正在考虑是否可以使用 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,所以最初我想到了以下内容(有些不合理的逻辑),但是由于未关闭的 html 标签,这将无法在 Razor 中验证。

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 还是很陌生,所以不太确定。

如有任何建议,我们将不胜感激。

请您参考如下方法:

您可以使用以下技术将它们分成几组:

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> 
 }