简体   繁体   English

如何将锯齿状数组转换为2D数组?

[英]How to convert jagged array to 2D array?

I have a file file.txt with the following: 我有一个文件file.txt以下各项:

6,73,6,71 
32,1,0,12 
3,11,1,134 
43,15,43,6 
55,0,4,12 

And this code to read it and feed it to a jagged array: 并通过以下代码读取它并将其提供给锯齿状数组:

    string[][] arr = new string[5][];
    string[] filelines = File.ReadAllLines("file.txt");
    for (int i = 0; i < filelines.Length; i++) 
    {
        arr[i] = filelines[i].Split(',').ToArray();
    }

How would I do the same thing, but with a 2D array? 如果使用2D阵列,我将如何做同样的事情?

Assuming you know the dimensions of your 2D array (or at least the maximum dimensions) before you start reading the file, you can do something like this: 假设您在开始读取文件之前了解 2D数组的尺寸(或至少是最大尺寸),则可以执行以下操作:

string[,] arr = new string[5,4];
string[] filelines = File.ReadAllLines("file.txt");
for (int i = 0; i < filelines.Length; i++) 
{
    var parts = filelines[i].Split(',');    // Note: no need for .ToArray()
    for (int j = 0; j < parts.Length; j++) 
    {
        arr[i, j] = parts[j];
    }
}

If you don't know the dimensions, or if the number of integers on each line may vary, your current code will work, and you can use a little Linq to convert the array after you've read it all in: 如果您不知道尺寸,或者每行整数的数量可能有所不同,那么您当前的代码将起作用,并且在阅读完所有内容后可以使用一点Linq来转换数组:

string[] filelines = File.ReadAllLines("file.txt");
string[][] arr = new string[filelines.Length][];
for (int i = 0; i < filelines.Length; i++) 
{
    arr[i] = filelines[i].Split(',');       // Note: no need for .ToArray()
}

// now convert
string[,] arr2 = new string[arr.Length, arr.Max(x => x.Length)];
for(var i = 0; i < arr.Length; i++)
{
    for(var j = 0; j < arr[i].Length; j++)
    {
        arr2[i, j] = arr[i][j];
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM