在我的if语句中,我增加了计数器的值。我使用var计数器作为子类别的索引。在if语句之后它从我的循环中跳出来。我希望它开始循环子类别[1]或[2]等。我如何继续循环索引1,2,3为我的子类别列表?
int counter = 0;
int eachCounter = 0;
foreach (var item in filteredList[0].subcategories[counter].questionanswer)
{
int questionsCounter = filteredList[0].subcategories[counter].questionanswer.Count;
eachCounter++;
if (eachCounter.Equals(questionsCounter))
{
counter++;
eachCounter = 0;
}
}
答案 0 :(得分:1)
只需使用for
,因为这不会起作用。 foreach
将在第一次迭代时迭代初始questionanswer
,它不会在下一次迭代中继续进行。
for (int counter = 0; counter < filteredList[0].subcategories.Count; counter++)
{
var item = filteredList[0].subcategories[counter].questionanswer;
}
如果要迭代两个列表(内部和外部列表),请使用两个foreach
语句或for
循环。
答案 1 :(得分:0)
使用for循环
int eachCounter = 0;
for(int i = 0; i < filteredList[0].subcategories[i].questionanswer.Count; i++)
{
int questionsCounter = filteredList[0].subcategories[i].questionanswer.Count;
eachCounter++; // I am not sure why you are doing this or what the purpose is
if (eachCounter.Equals(questionsCounter))
{
eachCounter = 0;
}
}
答案 2 :(得分:0)
使用每个以这种方式循环遍历filteredList[0].subcategories
数组:
int counter = 0;
int eachCounter = 0;
foreach (var item in filteredList[0].subcategories)
{
// item is filteredList[0].subcategories[0], filteredList[0].subcategories[1] and so on.
int questionsCounter = item.questionanswer.Count;
eachCounter++;
if (eachCounter.Equals(questionsCounter))
{
counter++;
eachCounter = 0;
}
}
我不知道你的程序背后的逻辑,我看到你使用counter
作为循环变量并在其间进行更改,因此它可能不会遍历filteredList[0].subcategories[]
的所有元素连续。但是,如果您想使用filteredList[0].subcategories[]
串行遍历foreach
的所有元素,则完成此操作。
编辑:
遍历子类别[0],[1]等等:
foreach (var item in filteredList[0].subcategories)
{
// item is filteredList[0].subcategories[0], filteredList[0].subcategories[1] and so on.
foreach(element in item)
{
//element is item[0], item[1] and so on i.e
// filteredList[0].subcategories[0].questionAnswer[0]
// filteredList[0].subcategories[0].questionAnswer[1]
// filteredList[0].subcategories[0].questionAnswer[2]
// .
// .
// filteredList[0].subcategories[1].questionAnswer[0]
// filteredList[0].subcategories[1].questionAnswer[1]
// .
// .
}
}