c# - 当最后一项匹配时循环列表<string>

标签 c# asp.net-mvc-4

我有相当简单的 List<string>包含阅读类型 - 出于显示目的,我将单独显示这些类型,而不是使用默认构造函数:

List<string> staticSubjects = new List<string>();

staticSubjects.Add("Comic Books & Graphic Novels");
staticSubjects.Add("Literature");
staticSubjects.Add("Mystery");
staticSubjects.Add("Romance");  
staticSubjects.Add("Science Fiction & Fantasy");
staticSubjects.Add("Suspense & Thriller");
staticSubjects.Add("Westerns");
staticSubjects.Add("Biography & Autobiography");
staticSubjects.Add("Careers");
staticSubjects.Add("Computers & Technology");

这个驱动器是每个类型的 (8) 个标题的列表,我们让用户有机会循环浏览所有这些类型以查看所有这些标题。

在表单本身,当用户点击“显示更多”时,我将传递我们正在显示标题的当前类型,并移至下一个:

var currentGenreIdx = genresToLoad.IndexOf(currentGenre);

// get the next genre based on the index
var nextGenre = genresToLoad[currentGenreIdx + 1];

// set the titles accordingly
titleList = allTitles.Where(x => x.genre.ToLower() == nextGenre.ToLower()).ToList();

现在显然这段代码是错误的,因为最终索引超出了范围。

我的问题是:

假设用户正在使用我的最后一个类型“计算机与技术”,如果我向它提供最后一个项目的索引,是否可以使用自动从列表开头开始的内容?

最佳答案

我认为您正在寻找 MOD 运算符(C# 中的 %):

genresToLoad[(currentGenreIdx + 1) % genresToLoad.Count];

关于c# - 当最后一项匹配时循环列表<string>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18235833/

相关文章:

c# - 为自定义复选框生成 OnCheckedChanged

c# - WPF/XAML 将元素的宽度绑定(bind)到屏幕大小的一部分

asp.net-mvc-4 - 模板内的 MVC 助手

c# - 为什么 .NET MVC 4 从 GET 查询字符串而不是模型联编程序中获取值

c# - 为什么我必须渲染我的 Bundle 两次?

asp.net-mvc-4 - 外部登录帐户与本地登录帐户

c# - Windows 应用程序认证工具包失败 : Multi user session test

c# - 对实体执行 CRUD 操作的最佳实践( Entity Framework )

c# - 赢 8/WP 8 : MMVM Framework?

javascript - ASP.NET MVC - Backbone js - 组织多页面 mvc 应用程序