2013-11-01 86 views
0


我有一個多維鋸齒狀字符串數組:返回多維交錯數組在C#中的數組

string[,][] MDJA = 
{ 
    {new string[]{"a", "b"}, new string[]{"c", "d"}, new string[]{"e", "f"}}, 
    {new string[]{"g", "h"}, new string[]{"j", "i"}, new string[]{"k", "l"}}, 
    {new string[]{"m", "n"}, new string[]{"o", "p"}, new string[]{"q", "r"}} 
} 

我使用的for循環到陣列的位置比較陣列內得到陣列我在找,但MDJA是在一個方法中,我希望它返回特定的數組。作爲一個例子,我可能要返回

new string[]{"m", "n"} 

通常我會在多維數組做到這一點:

for (byte i = 0; i < 3; i++) 
{ 
    if (var1[x] == var2[i]) 
    { 
     return answers[y,i] 
    } 
} 

但在使用它們時我以前沒有使用交錯數組和多維它使人們很難獲得信息。

P.S 4個變量是方法中的參數,var1和var2是字符串數組,x/y是整數。

謝謝你的幫助。

+2

目前還不清楚你在問什麼。如果我沒有弄錯,在你的例子中,你希望帶有'{「m」,「n」}'的數組從string [] myMethod(string [] var1,string [] var2 ,int x,int y)'。應該發生什麼參數值? –

回答

1

我不太清楚你的方法的邏輯是什麼樣子,但是對於元素訪問它應該是很簡單的:

for (int i = 0; i < MDJA.GetLength(0); i++) 
{ 
    for (int j = 0; j < MDJA.GetLength(1); j++) 
    { 
     // Your compare logics go here 
     // 
     bool found = i == 2 && j == 0; 
     if (found) 
     { 
      return MDJA[i, j]; 
     } 
    } 
} 

這將返回string[]{"m", "n"}

0

我以前做過這件事,唉,我沒有在這裏與我的代碼。

構建一個遞歸地調用自身,測試數組元素是否是一個數組本身,如果它不是一個實用的方法(等的值)將其添加到列表中,否則所述子/子陣列傳遞給遞歸方法。

提示,請使用Array對象作爲此方法的參數,而不是定義的int[,][]數組,因此可以傳遞任何形式的int[,][][][,,,][][,],並且仍然可以工作。

而對於您的問題,您將不得不檢測您希望停止從鋸齒形數組轉換爲數值的級別,然後以簡化的數組形式返回這些鋸齒形數組。

我稍後會發布我的代碼,它可能會幫助你。

public static int Count(Array pValues) 
    { 
     int count = 0; 

     foreach(object value in pValues) 
     { 
      if(value.GetType().IsArray) 
      { 
       count += Count((Array) value); 
      } 
      else 
      { 
       count ++; 
      } 
     } 

     return count; 
    }