[英]How to continue iteration in nested foreach
Here is my simple example: 这是我的简单示例:
IList<string> files = new string[] { "file1", "file2", "file3" };
IList<string> words = new string[] { "first", "second", "third", "fourth", "fifth", "sixth" };
foreach (var file in files) {
int i = 1;
foreach (var word in words) {
MessageBox.Show(i.ToString());
i++;
}
}
After every iteration, I want to see in the MessageBox 1
, 2
, 3
, 4
, 5
, 6
, 7
, 8
, 9
, 10
, 11
, 12
, 13
, 14
, 15
, 16
, 17
, 18
but it gives me 3 times 1
, 2
, 3
, 4
, 5
, 6
每次迭代后,我想在MessageBox看到1
, 2
, 3
, 4
, 5
, 6
, 7
, 8
, 9
, 10
, 11
, 12
, 13
, 14
, 15
, 16
, 17
, 18
,但它给我3次1
, 2
, 3
, 4
, 5
, 6
Is it possible which I want? 我可以要吗?
The reason why the counter " resets " itself is because you instruct it to do so: 计数器本身“ 重置 ”的原因是因为您指示它这样做:
foreach (var file in files) {
int i = 1; //<--- for each file, reset the counter i to 1
foreach (var word in words) {
MessageBox.Show(i.ToString());
i++;
}
}
You can get the behavior you aim by initializing the counter outside the outer loop: 您可以通过在外部循环外部初始化计数器来获得您想要的行为:
int i = 1; //<--- initialize outside outer loop
foreach (var file in files) {
foreach (var word in words) {
MessageBox.Show(i.ToString());
i++;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.