C# 具有动态索引的Foreach循环
在if语句中,我增加了counter的值。我使用var计数器作为子类别的索引。在if语句之后,它从我的循环中跳出。我希望它开始循环子类别[1]或[2]等。如何继续循环子类别列表的索引1、2、3C# 具有动态索引的Foreach循环,c#,foreach,C#,Foreach,在if语句中,我增加了counter的值。我使用var计数器作为子类别的索引。在if语句之后,它从我的循环中跳出。我希望它开始循环子类别[1]或[2]等。如何继续循环子类别列表的索引1、2、3 int counter = 0; int eachCounter = 0; foreach (var item in filteredList[0].subcategories[counter].questionanswer) { int questionsCounter = filteredLi
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;
}
}
使用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;
}
}
int-eachCounter=0;
对于(int i=0;i
只需为使用一个,因为这是行不通的。在第一次迭代中,foreach
将迭代初始的questionresponse
,在下一次迭代中它将不再继续
for (int counter = 0; counter < filteredList[0].subcategories.Count; counter++)
{
var item = filteredList[0].subcategories[counter].questionanswer;
}
for(int counter=0;counter
如果要在两个列表(内部和外部列表)上迭代,请使用两个foreach
语句或for
循环。使用for each通过过滤器列表[0]循环。子类别以这种方式排列:
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;
}
}
我不知道您的程序背后的逻辑,我看到您正在使用计数器
作为循环变量,并在循环变量之间进行更改,因此它可能不会连续迭代过滤器列表[0]的所有元素。子类别[]
。但是,如果要使用foreach
连续遍历filteredList[0]子类别[]
的所有元素,则其操作方式如下
编辑:
用于遍历子类别[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]
// .
// .
}
}
只是用来做什么?为什么它是一个foreach你甚至不用item?为什么你用foreach循环而不是for循环?默认情况下,For带有一个可用的索引。在子类别[0]中,我还需要循环遍历该列表,这就是为什么我使用counter,然后使用2个循环,一个用于遍历子类别,另一个用于遍历子类别[0]。使用计数器并尝试使用单个循环遍历列表列表在代码中是非常复杂的,而且性能没有任何提高。我已经更新了答案,以便遍历子类别[0]、[1]。