[英]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());
使用“ 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.