以下是我的简单示例:
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++;
}
}
每次迭代后,我想在MessageBox 1
,2
,3
,4
,5
,6
中看到, 7
,8
,9
,10
,11
,12
,13
,14
,{{ 1}},15
,16
,17
但它给了我3次18
,1
,2
,3
,4
,5
我有可能吗?
答案 0 :(得分:8)
计数器&#34; 重置&#34;本身是因为你指示它这样做:
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++;
}
}
您可以通过在外部循环外部初始化计数器来获得您的目标:
int i = 1; //<--- initialize outside outer loop
foreach (var file in files) {
foreach (var word in words) {
MessageBox.Show(i.ToString());
i++;
}
}