这是我的简单示例:
IListfiles = new string[] { "file1", "file2", "file3" }; IList 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
,15
,16
,17
,18
但它给了我3次1
,2
,3
,4
,5
,6
我想要的可能吗?
计数器" 重置 "本身的原因是因为你指示它这样做:
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++; } }