C# 字符串数组GetLength(1)工作选项

C# 字符串数组GetLength(1)工作选项,c#,arrays,C#,Arrays,我正在使用System.IO.File.ReadAllLines读取.txt文件。 它返回一个字符串[],但人类也可以将其称为2D字符数组,这正是我试图将其放入的内容。我试图找出这个数组的第二维度,尽可能抽象 string[] textFile = System.IO.File.ReadAllLines(path); char[,] charGrid = new char[textFile.GetLength(0), textFile.GetLength(1)]; IndexOutOfRang

我正在使用
System.IO.File.ReadAllLines
读取.txt文件。 它返回一个
字符串[]
,但人类也可以将其称为2D
字符
数组,这正是我试图将其放入的内容。我试图找出这个数组的第二维度,尽可能抽象

string[] textFile = System.IO.File.ReadAllLines(path);
char[,] charGrid = new char[textFile.GetLength(0), textFile.GetLength(1)];
IndexOutOfRangeException:索引超出了数组的边界。

我知道我可以循环遍历数组并自己找到第二维度的长度,但我正在寻找一个简单、可读和抽象的解决方案

ps:我的输入txt文件:

#111
1-1
-00
10-

您需要找到文件中最长行的长度(因为这种方法本质上提供了一个锯齿状数组)。这可以通过以下代码位完成:

int dimension = textFile.Max(line => line.Length);
您需要使用System.Linq添加
以使用
Max
,它将返回
textFile
数组中所有字符串的最大
Length
值。
然后将
维度
(或任何你想称之为维度的东西)放到你的char数组声明中

char[,] charGrid = new char[szTest.Length, dimension];

此解决方案假定每行具有相同数量的字符

using System;
using System.IO;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            String path = @"input.txt";
            string[] textFile = File.ReadAllLines(path);
            char[,] charGrid = new char[textFile.Length, textFile[0].Length];
            int i, j;
            i = 0;
            foreach (string line in textFile)
            {
                j = 0;
                foreach (char c in line)
                {
                    charGrid[i, j] = c;
                    j++;
                }
                i++;
            }
            Console.WriteLine(charGrid[0,0] +  "" + charGrid[0, 1] + "" + charGrid[0, 2]);
            Console.WriteLine(charGrid[1, 0] + "" + charGrid[1, 1] + "" + charGrid[1, 2]);
            Console.WriteLine(charGrid[2, 0] + "" + charGrid[2, 1] +  "" + charGrid[2, 2]);
            Console.ReadLine();
        }
    }
}

它不是二维阵列,更像是一维锯齿阵列。如果你想让它成为一个2d数组,你需要计算出文件中任何给定行的最大长度,以计算出该维度应该是多少。这正是我想要的。您还应该添加,您需要
使用System.Linq