c# - 如何在 C# 中使用列表创建循环

标签 c# asp.net-mvc-3 list razor

在我的 asp mvc 3 应用程序中,我想显示相册。因此相册中将出现所选图片和其他图片的缩略图列表。用户将能够看到的缩略图列表仅包含 8 张图片,其他所有图片都将被隐藏。我想要的是从所选项目开始此列表,当列表到达末尾但未完成所有项目时,它将从头重新开始。

我设法用这段代码做到了,但我发现它又快又脏。是否有任何内置的 C# 函数可用于执行此操作?

@{int i = 0;}
@foreach (AlbumPhoto albmphoto in Model.AlbumPhotoList
  .Where(p => p.AlbumPhotoId > int.Parse(SinglePhoto))
  .OrderBy(p => p.AlbumPhotoId))
{
    i++;
    string show = "none";
    if (i < 8)
    {
        show = "block";
    }
    <a href="#" style="display: @show">
        <img src="@Url.Content(albmphoto.AlbumPhotoPath)" width="70" height="47" border="0" alt="@albmphoto.AlbumPhotoDescription" />
    </a>                   
}

@foreach (AlbumPhoto albmphoto in Model.AlbumPhotoList
  .Where(p => p.AlbumPhotoId < int.Parse(SinglePhoto))
  .OrderBy(p => p.AlbumPhotoId))
{
    i++;
    string show = "none";
    if (i < 8)
    {
        show = "block";
    }
    <a href="#" style="display: @show">
        <img src="@Url.Content(albmphoto.AlbumPhotoPath)" width="70" height="47" border="0" alt="@albmphoto.AlbumPhotoDescription" />
    </a>                   
}

最佳答案

我不认为有任何内置的东西可以在 IEnumerable 上执行“rollover foreach”,但是你可以用 Concat 稍微不那么令人厌恶地解决它,本质上再次将对象集附加到自身。

var photos = Model.AlbumPhotoList
  .Where(p => p.AlbumPhotoId < int.Parse(SinglePhoto))
  .OrderBy(p => p.AlbumPhotoId);

@foreach(var albumphoto in photos.Concat(photos))
{
  i++;
      string show = "none";
      if (i < 8)
      {
          show = "block";
      }
      <a href="#" style="display: @show">
          <img src="@Url.Content(albmphoto.AlbumPhotoPath)" width="70" height="47" border="0" alt="@albmphoto.AlbumPhotoDescription" />
      </a>       
}

然后如果它走到尽头,它会翻滚到下一组。

或者,作为更好的解决方案,您可以 ToList IEnumerable 并使用 % 进行更好的索引:

var photos = Model.AlbumPhotoList
      .Where(p => p.AlbumPhotoId < int.Parse(SinglePhoto))
      .OrderBy(p => p.AlbumPhotoId)
      .ToList();

@for(int i = 0; i < 8; ++i)
{
 if(i < 8)
 {
  show = "block";
 }
 var albumphoto = photos[i % photos.Count];
 <a href="#" style="display: @show">
  <img src="@Url.Content(albmphoto.AlbumPhotoPath)" width="70" height="47" border="0" alt="@albmphoto.AlbumPhotoDescription" />
 </a> 
}

关于c# - 如何在 C# 中使用列表创建循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12465241/

相关文章:

python - 完全循环具有不同起始索引的列表

python - 将列表转换为嵌套字典

c# - 使用结构而不是给构造函数 8 个参数是否正确?

c# - Dapper 反序列化 XML

asp.net-mvc-3 - ASP.Net MVC 架构 - 绕过 Controller 层?

asp.net-mvc - 在 Razor View 中启用客户端验证 (ASP MVC 3)

c# - 编写新的自定义 mvc4 成员提供程序

c# - 如何验证 C# 中的消息框弹出窗口?

c# - XAML 是否有用于 Debug模式的条件编译器指令?

Python 3 正在将元素添加到列表中,而不管 dict 中使用的键是什么