如何交错数组转换为二维数组? [英] How to convert jagged array to 2D array?

查看:208
本文介绍了如何交错数组转换为二维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件 file.txt的为以下内容:

I have a file file.txt with the following:

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

这code读它,并将其输送到交错数组:

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?

推荐答案

假设你的知道的你的二维数组的大小(或至少最大尺寸),你开始读文件之前,可以做这样的事情:

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:

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

如果您不知道的尺寸,或者整数每行的数量可能会有所不同,您目前的code会的工作,你可以用一点点的LINQ到数组转换成你读过之后尽在:

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:

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

这篇关于如何交错数组转换为二维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆