如何在嵌套的foreach中继续迭代

时间:2016-01-03 13:30:15

标签: c# loops iteration

以下是我的简单示例:

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 123456中看到, 7891011121314,{{ 1}},151617但它给了我3次1812345

我有可能吗?

1 个答案:

答案 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++;
    }
}