繁体   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