2016-12-05 59 views
1

我是C#的新手,並試圖學習如何發送一個2D數組的單個行到一個函數。我有一個3行2列的二維數組。如果我想將第三行發送給名爲calculate的函數,請告訴我如何執行此操作。發送一個二維數組的一行到c中的函數#

namespace test 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string[,] array2Db = new string[3, 2] { { "one", "two" }, { "three", "four" }, { "five", "six" } }; 
      calculate(array2Db[2,0]); //I want to send only the 3rd row to this array 
      //This array may contain millions of words. Therefore, I can't pass each array value individually 
     } 

     void calculate(string[] words) 
     { 
      for (int i = 0; i < 2; i++) 
      { 
       Console.WriteLine(words); 
      } 
     } 
    } 
} 

任何幫助,將不勝感激

回答

1

使用 'Y' 尺寸的長度(X = 0,Y = 1),我們創建的數字0和Y的長度之間的可枚舉使用它,這將作爲一個循環來遍歷和檢索的所有元素,其中「X」尺寸= 2(在基於0收集第三)

var yRange = Enumerable.Range(0, array2Db.GetLength(1)); 
var result = yRange.Select(y => array2Db[2, y]); 

或者你的情況(I改變由計算接收到的參數()從字符串數組的IEnumerable,以避免無謂的類型轉換:

calculate(Enumerable.Range(0, array2Db.GetLength(1)).Select(y => array2Db[2, y])); 

static void calculate(IEnumerable<string> words) 
{ 
    foreach(string word in words) 
     Console.WriteLine(word); 
} 

編輯:試圖添加一些澄清

+0

這是一個很好的例子,但與問題的例子相比。這可能很難理解。 –

+0

@ Innat3感謝您舉例說明。當我運行這段代碼時,它給出了一個輸出如下:'System.String []' 'System.String []' –

+0

@DP。啊我發現這個問題,你沒有在** calculate()**方法中顯示數組元素時傳遞索引值。我將添加更新 – Innat3

2

array2Db[2, 0]將使你在第三行第一列,這是一個字符串實際上,不是數組作爲方法calculate期待一個值,如果你想通過完整的一行意味着你必須調用類似如下的方法:

calculate(new []{array2Db[2, 0],array2Db[2, 1]}); 

這將通過第三排的兩列作爲數組調用方法。 A working Example here

6

您可以製作一個擴展方法來枚舉您的特定行。

public static class ArrayExtensions 
{ 
    public static IEnumerable<T> GetRow<T>(this T[,] items, int row) 
    { 
     for (var i = 0; i < items.GetLength(1); i++) 
     { 
      yield return items[row, i]; 
     } 
    } 
} 

然後就可以用

string[,] array2Db = new string[3, 2] { { "one", "two" }, { "three", "four" }, { "five", "six" } }; 
calculate(array2Db.GetRow(2).ToArray()); 
+1

尼斯耐用的答案。 +1,你可能想要將'calculate(string [] words)'簽名更改爲'calculate(IEnumerable words)'或稱之爲:'calculate(array2Db.GetRow(2).ToArray());' –

+0

好點,將擴展中的數組添加到數組和動態數組維度中。 –