2012-02-15 6 views
11
foreach (String s in arrayOfMessages) 
{ 
    System.Console.WriteLine(s); 
} 

string[,] arrayOfMessages이 매개 변수로 전달됩니다.다차원 배열을 어떻게 반복합니까?

arrayOfMessages[0,i]arrayOfMessages[n,i]의 문자열을 확인하고 싶습니다. 여기서 n은 배열의 최종 색인입니다.

+1

왜 인덱스가있는 루프를 사용하지 않는 것이 좋습니까? –

답변

30

간단하게 두 개의 중첩 for 루프를 사용합니다. 치수의 크기를 얻으려면, 당신은 GetLength()를 사용할 수 있습니다

for (int i = 0; i < arrayOfMessages.GetLength(0); i++) 
{ 
    for (int j = 0; j < arrayOfMessages.GetLength(1); j++) 
    { 
     string s = arrayOfMessages[i, j]; 
     Console.WriteLine(s); 
    } 
} 

이 실제로 string[,]을 가정합니다. .Net에서는 0에서 인덱싱되지 않은 다차원 배열을 가질 수도 있습니다.이 경우 C#에서 Array으로 표현되어야하고 GetLowerBound()GetUpperBound()을 사용해야 각 차원의 경계를 가져올 수 있습니다. 이 같은

5

foreach - 배열의 각 차원에 하나씩 중첩 된 for 루프를 사용하지 마십시오.

GetLength 메서드를 사용하여 각 측정 기준의 요소 수를 얻을 수 있습니다.

MSDN의 Multidimensional Arrays (C# Programming Guide)을 참조하십시오. 루프 중첩으로

7

:

for (int row = 0; row < arrayOfMessages.GetLength(0); row++) 
{ 
    for (int col = 0; col < arrayOfMessages.GetLength(1); col++) 
    { 
     string message = arrayOfMessages[row,col]; 
     // use the message 
    }  
} 
1

뭔가 작동합니다 :

int length0 = arrayOfMessages.GetUpperBound(0) + 1; 
int length1 = arrayOfMessages.GetUpperBound(1) + 1; 

for(int i=0; i<length1; i++) { string msg = arrayOfMessages[0, i]; ... } 
for(int i=0; i<length1; i++) { string msg = arrayOfMessages[length0-1, i]; ... } 
1

당신은 다차원 배열을 실행하려면 아래의 코드를 사용할 수 있습니다.

foreach (String s in arrayOfMessages) 
{ 
    System.Console.WriteLine("{0}",s); 
} 
0

당신이 당신의 문제에 대한 적절한 답을 찾을 것 같습니다하지만, 제목이 다차원 배열을 요구하기 때문에 (나는 2 이상의과 같이하는), 그리고 이것은 내가 가진 첫 번째 검색 결과입니다

public static class MultidimensionalArrayExtensions 
{ 
    /// <summary> 
    /// Projects each element of a sequence into a new form by incorporating the element's index. 
    /// </summary> 
    /// <typeparam name="T">The type of the elements of the array.</typeparam> 
    /// <param name="array">A sequence of values to invoke the action on.</param> 
    /// <param name="action">An action to apply to each source element; the second parameter of the function represents the index of the source element.</param> 
    public static void ForEach<T>(this Array array, Action<T, int[]> action) 
    { 
     var dimensionSizes = Enumerable.Range(0, array.Rank).Select(i => array.GetLength(i)).ToArray(); 
     ArrayForEach(dimensionSizes, action, new int[] { }, array); 
    } 
    private static void ArrayForEach<T>(int[] dimensionSizes, Action<T, int[]> action, int[] externalCoordinates, Array masterArray) 
    { 
     if (dimensionSizes.Length == 1) 
      for (int i = 0; i < dimensionSizes[0]; i++) 
      { 
       var globalCoordinates = externalCoordinates.Concat(new[] { i }).ToArray(); 
       var value = (T)masterArray.GetValue(globalCoordinates); 
       action(value, globalCoordinates); 
      } 
     else 
      for (int i = 0; i < dimensionSizes[0]; i++) 
       ArrayForEach(dimensionSizes.Skip(1).ToArray(), action, externalCoordinates.Concat(new[] { i }).ToArray(), masterArray); 
    } 

    public static void PopulateArray<T>(this Array array, Func<int[], T> calculateElement) 
    { 
     array.ForEach<T>((element, indexArray) => array.SetValue(calculateElement(indexArray), indexArray)); 
    } 
} 

사용 예 :

var foo = new string[,] { { "a", "b" }, { "c", "d" } }; 
foo.ForEach<string>((value, coords) => Console.WriteLine("(" + String.Join(", ", coords) + $")={value}")); 
// outputs: 
// (0, 0)=a 
// (0, 1)=b 
// (1, 0)=c 
// (1, 1)=d 

// Gives a 10d array where each element equals the sum of its coordinates: 
var bar = new int[4, 4, 4, 5, 6, 5, 4, 4, 4, 5]; 
bar.PopulateArray(coords => coords.Sum()); 

일반 아이디어 차원을 통해 아래로 재귀하는 것입니다 검색하면, 나는 내 솔루션을 추가 할 것 . 함수가 효율성 상을 얻지는 못할 것이라고 확신하지만, 이는 내 격자에 대한 일회성 초기화 프로그램으로 작동하며 값과 인덱스를 제공하는 멋진 ForEach를 제공합니다. 필자가 해결하지 못한 주된 단점은 Array에서 T를 자동으로 인식하도록하는 것입니다. 따라서 형식 안전성에 관해서는주의가 필요합니다.

관련 문제