简体   繁体   English

将由逗号分隔的字符串 [] 数组解析为二维数组 C#

[英]Parse array of string [] separated by comma to 2d array C#

I have a large array of say length 3 in C# filled with strings:我在 C# 中有一个长度为 3 的大数组,其中填充了字符串:

The strings:字符串:

myArray[0,0] contains: "1,11,2,18,4" myArray[0,0] 包含:“1,11,2,18,4”

myArray[0,1] contains: "2,21,12,138,14" myArray[0,1] 包含:“2,21,12,138,14”

myArray[0,2] contains: "1,131,21,138,24" myArray[0,2] 包含:“1,131,21,138,24”

I want to go through this array of strings (so 0,0 to 0,2. Or if I have a million, [0,0] to [0,999999]), split up the numbers by their commas, and generate basically this:我想通过这个字符串数组(所以 0,0 到 0,2。或者如果我有一百万,[0,0] 到 [0,999999]),用逗号分割数字,并基本上生成这个:

var a = new int [,] { {1 , 11, 2, 18, 4 }, {2, 21, 12, 138, 14}, {1, 131, 21, 138, 24 } };

This problem is not easily solved with LINQ, since the output must be a 2-dimensional array.这个问题用 LINQ 不容易解决,因为输出必须是一个二维数组。 Therefore I'm using the good old loops.因此,我正在使用旧的循环。 I'm also using a one-dimensional string array as input.我也使用一维字符串数组作为输入。 For the code to work, all lines must contain the same number of integers (given as SubArrayLength here):要使代码正常工作,所有行必须包含相同数量的整数(此处为SubArrayLength ):

const int SubArrayLength = 5;

string[] myArray = { "1,11,2,18,4", "2,21,12,138,14", "1,131,21,138,24" };

var a = new int[myArray.Length, SubArrayLength];
for (int i = 0; i < myArray.Length; i++) {
    var numbers = myArray[i].Split(',');
    for (int j = 0; j < SubArrayLength; j++) {
        a[i, j] = Int32.Parse(numbers[j]);
    }
}

If it is not a problem for you to have a jagged array (ie, an array of arrays) instead of multi-dimensional array, you can use this LINQ code:如果使用锯齿状数组(即数组的数组)而不是多维数组对您来说不是问题,则可以使用以下 LINQ 代码:

string[] myArray = { "1,11,2,18,4", "2,21,12,138,14", "1,131,21,138,24" };

var a = myArray
    .Select(s => s.Split(',').Select(n => Int32.Parse(n)).ToArray())
    .ToArray();

In this second example a is of type int[][] instead of int[,] .在第二个示例中, a的类型为int[][]而不是int[,] The lengths of the nested arrays can differ.嵌套数组的长度可以不同。

For future people, I just coded it the long way.对于未来的人,我只是编码它很长的路要走。

int[,] TEST1 = new int[e, 30];
var test = (Array.ConvertAll(testOfIt.Split(','), int.Parse));

for (int i=0; i<3; i++)
{
            for(int j=0; j<5; j++)
            {
                TEST1[i, j] = test[j];
            }
}

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

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