C#中如何从二维数组中打印首个一维子数组?
解决二维数组打印首个行元素的问题
你的核心误解在于:string[,]是多维矩形数组,而非交错数组(string[][])。这类数组中不存在“一维子数组”的概念,每个元素都是单个字符串,所以你无法直接提取出一个一维子数组。原代码报错的原因是GetValue(0)参数不完整(多维数组需要指定所有维度的索引,比如GetValue(0,0)只会返回单个元素"Bob"),且string.Join需要传入可枚举集合而非单个元素。
方案1:遍历第一行元素(基础写法)
通过循环遍历第一行的所有列,收集元素后再拼接输出:
string[,] customerNames = new string[2,2] { { "Bob", "Smith" }, { "Sally", "Smith" } }; List<string> firstRowElements = new List<string>(); // 获取列数,遍历第一行的每一列 for (int col = 0; col < customerNames.GetLength(1); col++) { firstRowElements.Add(customerNames[0, col]); } Console.WriteLine($"[{string.Join(", ", firstRowElements)}]");
方案2:用LINQ简化代码(需要引入System.Linq)
通过Enumerable.Range生成列索引,再映射到第一行的元素:
using System.Linq; string[,] customerNames = new string[2,2] { { "Bob", "Smith" }, { "Sally", "Smith" } }; var firstRow = Enumerable.Range(0, customerNames.GetLength(1)) .Select(col => customerNames[0, col]); Console.WriteLine($"[{string.Join(", ", firstRow)}]");
可选:改用交错数组(如果符合你的场景)
如果你原本就需要“数组中的每个元素是一维数组”的结构,可以使用交错数组string[][],此时你的初始思路就能直接生效:
string[][] customerNames = new string[][] { new[] { "Bob", "Smith" }, new[] { "Sally", "Smith" } }; Console.WriteLine($"[{string.Join(", ", customerNames[0])}]");
以上三种方式都能输出你期望的[Bob, Smith]。
内容的提问来源于stack exchange,提问作者Tom Obungu
相关产品推荐
相关产品推荐

