我有相当简单的 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/