【问题标题】:Sending one row of a 2D array to a function in c#将一行二维数组发送到c#中的函数
【发布时间】:2017-04-19 13:35:29
【问题描述】:

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

任何帮助将不胜感激

【问题讨论】:

    标签: c# arrays


    【解决方案1】:

    array2Db[2, 0] 将在第三行第一列给你一个值,这实际上是一个字符串,而不是 calculate 所期望的方法的数组,如果你想传递完整的行意味着你必须调用方法如下:

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

    这会将第三行的两列作为数组传递给被调用的方法。一个working Example here

    【讨论】:

      【解决方案2】:

      您可以创建一个扩展方法来枚举您的特定行。

      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,您可能希望将 calculate(string[] words) 签名更改为 calculate(IEnumerable&lt;string&gt; words) 或将其命名为:calculate(array2Db.GetRow(2).ToArray());
      • 好点,在扩展中添加了强制转换为数组和动态数组维度。
      【解决方案3】:

      使用“Y”维度的长度(x = 0, y = 1),我们创建了一个介于 0 和 Y 长度之间的数字的 Enumerable,它将作为一个循环来迭代和检索所有存在“X”的元素' 维度 = 2(基于 0 的集合中的第三个)

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

      编辑:尝试添加一些说明

      【讨论】:

      • 这是一个很好的例子,但与问题的例子相比。这可能很难掌握。
      • @Innat3 感谢您提供示例。当我运行这段代码时,它会给出如下输出:System.String[]System.String[]
      • @DP。啊,我发现了问题,在 calculate() 方法中显示数组元素时,您没有传递索引值。我会添加更新
      • 感谢您提供详细信息并按照提问的方式回答我的问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-23
      • 2019-04-01
      相关资源
      最近更新 更多