Program Tip

중첩 된 Foreach 문을 사용하여 다차원 배열 반복

programtip 2020. 11. 7. 10:23
반응형

중첩 된 Foreach 문을 사용하여 다차원 배열 반복


나는 이것이 매우 간단한 질문이라고 생각하지만 아직 그것을 알아낼 수 없었습니다. 다음과 같은 2 차원 배열이있는 경우 :

int[,] array = new int[2,3] { {1, 2, 3}, {4, 5, 6} };

중첩 된 foreach을 사용하여 배열의 각 차원을 반복하는 가장 좋은 방법은 무엇입니까 ?


평면화 된 배열 인 것처럼 배열의 모든 항목을 반복하려면 다음을 수행하면됩니다.

foreach (int i in array) {
    Console.Write(i);
}

인쇄 할 것

123456

x 및 y 인덱스도 알고 싶다면 다음을 수행해야합니다.

for (int x = 0; x < array.GetLength(0); x += 1) {
    for (int y = 0; y < array.GetLength(1); y += 1) {
        Console.Write(array[x, y]);
    }
}

또는 들쭉날쭉 한 배열 (배열 배열)을 대신 사용할 수 있습니다.

int[][] array = new int[2][] { new int[3] {1, 2, 3}, new int[3] {4, 5, 6} };
foreach (int[] subArray in array) {
    foreach (int i in subArray) {
        Console.Write(i);
    }
}

또는

int[][] array = new int[2][] { new int[3] {1, 2, 3}, new int[3] {4, 5, 6} };
for (int j = 0; j < array.Length; j += 1) {
    for (int k = 0; k < array[j].Length; k += 1) {
        Console.Write(array[j][k]);
    }
}

2 차원 배열의 각 요소를 방문하는 방법은 다음과 같습니다. 이것이 당신이 찾던 것입니까?

for (int i=0;i<array.GetLength(0);i++)
{
    for (int j=0;j<array.GetLength(1);j++)
    {
        int cell = array[i,j];
    }
}

다차원 배열을 사용하면 동일한 방법을 사용하여 요소를 반복 할 수 있습니다. 예를 들면 다음과 같습니다.

int[,] numbers2D = new int[3, 2] { { 9, 99 }, { 3, 33 }, { 5, 55 } };
foreach (int i in numbers2D)
{
    System.Console.Write("{0} ", i);
}

이 예제의 출력은 다음과 같습니다.

9 99 3 33 5 55

참고 문헌


Java에서 다차원 배열은 배열의 배열이므로 다음이 작동합니다.

    int[][] table = {
            { 1, 2, 3 },
            { 4, 5, 6 },
    };
    for (int[] row : table) {
        for (int el : row) {
            System.out.println(el);
        }
    }

나는 이것이 오래된 게시물이라는 것을 알고 있지만 Google을 통해 찾았고 그것을 가지고 노는 후에 더 쉬운 해결책이 있다고 생각합니다. 내가 틀렸다면 '알고 싶습니다만, 이것은 적어도 내 목적을 위해 작동했습니다 (ICR의 응답을 기반으로 함).

for (int x = 0; x < array.GetLength(0); x++)
{
    Console.Write(array[x, 0], array[x,1], array[x,2]);
}

두 차원이 모두 제한되어 있으므로 둘 중 하나는 단순 숫자 일 수 있으므로 중첩 된 for 루프를 피하십시오. 저는 C #을 처음 접했음을 인정합니다. 그러니하지 말아야 할 이유가 있으면 알려주세요 ...


C #의 2D 배열은 중첩 된 foreach에 적합하지 않으며 들쭉날쭉 한 배열 (배열 배열)과 동일하지 않습니다. foreach를 사용하려면 이와 같이 할 수 있습니다.

foreach (int i in Enumerable.Range(0, array.GetLength(0)))
    foreach (int j in Enumerable.Range(0, array.GetLength(1)))
        Console.WriteLine(array[i, j]);

그러나 여전히 i와 j를 배열의 인덱스 값으로 사용합니다. for대신 가든 버라이어티 루프를 갔다면 가독성이 더 잘 보존 됩니다.


두 가지 방법:

  1. 배열을 들쭉날쭉 한 배열로 정의하고 중첩 된 foreach를 사용합니다.
  2. 배열을 정상적으로 정의하고 전체에 대해 foreach를 사용하십시오.

# 2의 예 :

int[,] arr = { { 1, 2 }, { 3, 4 } };
foreach(int a in arr)
    Console.Write(a);

출력은 1234입니다. 즉. i를 0에서 n으로, j를 0에서 n으로하는 것과 똑같습니다.


다음과 같은 확장 방법을 사용할 수 있습니다.

internal static class ArrayExt
{
    public static IEnumerable<int> Indices(this Array array, int dimension)
    {
        for (var i = array.GetLowerBound(dimension); i <= array.GetUpperBound(dimension); i++)
        {
            yield return i;
        }
    }
}

그리고:

int[,] array = { { 1, 2, 3 }, { 4, 5, 6 } };
foreach (var i in array.Indices(0))
{
    foreach (var j in array.Indices(1))
    {
        Console.Write(array[i, j]);
    }

    Console.WriteLine();
}

for 루프를 사용하는 것보다 약간 느리지 만 대부분의 경우 문제가되지 않습니다. 더 읽기 쉽게 만드는지 확실하지 않습니다.

C # 배열은 0부터 시작하지 않을 수 있으므로 다음과 같이 for 루프를 사용할 수 있습니다.

int[,] array = { { 1, 2, 3 }, { 4, 5, 6 } };
for (var i = array.GetLowerBound(0); i <= array.GetUpperBound(0); i++)
{
    for (var j= array.GetLowerBound(1); j <= array.GetUpperBound(1); j++)
    {
        Console.Write(array[i, j]);
    }

    Console.WriteLine();
}

LINQ .Cast<int>()사용 하여 2D 배열을 IEnumerable<int>.

LINQPad 예 :

var arr = new int[,] { 
  { 1, 2, 3 }, 
  { 4, 5, 6 } 
};

IEnumerable<int> values = arr.Cast<int>();
Console.WriteLine(values);

산출:

Sequence is 1,2,3,4,5,6


You can also use enumerators. Every array-type of any dimension supports the Array.GetEnumerator method. The only caveat is that you will have to deal with boxing/unboxing. However, the code you need to write will be quite trivial.

Here's the sample code:

class Program
{
    static void Main(string[] args)
    {
        int[,] myArray = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } };
        var e = myArray.GetEnumerator();

        e.Reset();

        while (e.MoveNext())
        {
            // this will output each number from 1 to 6. 
            Console.WriteLine(e.Current.ToString());
        }

        Console.ReadLine();
    }
}

int[,] arr =  { 
                {1, 2, 3},
                {4, 5, 6},
                {7, 8, 9}
              };
 for(int i = 0; i < arr.GetLength(0); i++){
      for (int j = 0; j < arr.GetLength(1); j++)
           Console.Write( "{0}\t",arr[i, j]);
      Console.WriteLine();
    }

output:  1  2  3
         4  5  6
         7  8  9

As mentioned elsewhere, you can just iterate over the array and it will produce all results in order across all dimensions. However, if you want to know the indices as well, then how about using this - http://blogs.msdn.com/b/ericlippert/archive/2010/06/28/computing-a-cartesian-product-with-linq.aspx

then doing something like:

var dimensionLengthRanges = Enumerable.Range(0, myArray.Rank).Select(x => Enumerable.Range(0, myArray.GetLength(x)));
var indicesCombinations = dimensionLengthRanges.CartesianProduct();

foreach (var indices in indicesCombinations)
{
    Console.WriteLine("[{0}] = {1}", string.Join(",", indices), myArray.GetValue(indices.ToArray()));
}

참고URL : https://stackoverflow.com/questions/2893297/iterate-multi-dimensional-array-with-nested-foreach-statement

반응형