我是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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激
您可以创建一个扩展方法来枚举特定的行.
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];
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以使用它
string[,] array2Db = new string[3, 2] { { "one", "two" }, { "three", "four" }, { "five", "six" } };
calculate(array2Db.GetRow(2).ToArray());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1462 次 |
| 最近记录: |