📜  foreach 两个数组 c# (1)

📅  最后修改于: 2023-12-03 14:41:18.648000             🧑  作者: Mango

使用foreach遍历两个数组(C#)

在C#中,我们可以通过foreach语句来遍历一个数组,也可以通过使用foreach嵌套语句来遍历两个数组。在这篇文章中,我们将介绍如何使用foreach遍历两个数组的方法。

定义两个数组

在我们开始使用foreach嵌套语句来遍历两个数组之前,我们需要定义这两个数组。下面是两个示例数组:

int[] arr1 = { 1, 2, 3, 4, 5 };
int[] arr2 = { 6, 7, 8, 9, 10 };
使用foreach遍历两个数组

要使用foreach遍历两个数组,我们可以将一个数组作为外层循环,另一个数组作为内层循环,如下所示:

foreach (int i in arr1)
{
    foreach (int j in arr2)
    {
        Console.WriteLine("i = {0}, j = {1}", i, j);
    }
}

上面的代码将会输出以下内容:

i = 1, j = 6
i = 1, j = 7
i = 1, j = 8
i = 1, j = 9
i = 1, j = 10
i = 2, j = 6
i = 2, j = 7
i = 2, j = 8
i = 2, j = 9
i = 2, j = 10
i = 3, j = 6
i = 3, j = 7
i = 3, j = 8
i = 3, j = 9
i = 3, j = 10
i = 4, j = 6
i = 4, j = 7
i = 4, j = 8
i = 4, j = 9
i = 4, j = 10
i = 5, j = 6
i = 5, j = 7
i = 5, j = 8
i = 5, j = 9
i = 5, j = 10
改变遍历的顺序

如果我们需要改变遍历的顺序,比如先遍历arr2,再遍历arr1,我们可以将上面的代码稍作修改:

foreach (int i in arr2)
{
    foreach (int j in arr1)
    {
        Console.WriteLine("i = {0}, j = {1}", i, j);
    }
}

这将会输出如下内容:

i = 6, j = 1
i = 6, j = 2
i = 6, j = 3
i = 6, j = 4
i = 6, j = 5
i = 7, j = 1
i = 7, j = 2
i = 7, j = 3
i = 7, j = 4
i = 7, j = 5
i = 8, j = 1
i = 8, j = 2
i = 8, j = 3
i = 8, j = 4
i = 8, j = 5
i = 9, j = 1
i = 9, j = 2
i = 9, j = 3
i = 9, j = 4
i = 9, j = 5
i = 10, j = 1
i = 10, j = 2
i = 10, j = 3
i = 10, j = 4
i = 10, j = 5
总结

在本文中,我们介绍了如何使用foreach语句来遍历两个数组,包括嵌套foreach语句以及如何改变遍历的顺序。这是C#中使用foreach的一个实际应用,也是我们在编写常规程序中经常会遇到的情境之一。