簡體   English   中英

將2D數組的一行發送到C#中的函數

[英]Sending one row of a 2D array to a function in c#

我是C#的新手,正在嘗試學習如何將2D數組的各個行發送到函數。 我有一個3行2列的二維數組。 如果我想將第三行發送給一個名為calculate的函數,請告訴我該如何做。

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);
            }
        }
    }
}

任何幫助將不勝感激

您可以使用擴展方法來枚舉特定行。

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());

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

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

它將第三行的兩列作為數組傳遞給被調用的方法。 這里工作示例

使用“ Y”維度的長度(x = 0,y = 1),我們創建了一個介於0和Y長度之間的數字的Enumerable,它將作為循環來迭代和檢索“ X”維度= 2(基於0的集合中的第3個)

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

或者在您的情況下(我將由calculate()接收的參數從字符串數組更改為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);
}

編輯:試圖添加一些澄清

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM