1

我有相当简单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();

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

我的问题是这样的

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

4

4 回答 4

4

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

genresToLoad[(currentGenreIdx + 1) % genresToLoad.Count];
于 2013-08-14T15:28:40.443 回答
3

您可以使用

var nextGenre = genresToLoad[(currentGenreIdx + 1) % genreCount];

哪里genreCount = genresToLoad.Count

于 2013-08-14T15:28:35.320 回答
2

是的,您可以使用该modulo函数,如果第一个参数除以第二个参数,该函数将返回剩余部分。代码如下:

// get the next genre based on the index
var nextGenre = genresToLoad[(currentGenreIdx + 1) % genresToLoad.Count()]; 
于 2013-08-14T15:28:51.193 回答
1
var nextGenre = genresToLoad[(currentGenreIdx + 1) % genresToLoad.Count];
于 2013-08-14T15:29:17.290 回答