首页 > 解决方案 > 从带分隔符的字符串创建多维数组

问题描述

我有一个逗号分隔的字符串,如下所示:

string myString = "1,a,b,C1,,#2,d,e,C2,,#3,f,g,C3,,#4,h,i,C4,,#";

这基本上是我使用阅读器从文件中读取的 csv 文件中的数据。

在上面的字符串中,',' 代表数据分隔符,而 '#' 代表文件的 EOL。

myString = myString.TrimEnd('#'); //Removing extra # in the end.
//Result of above 1,a,b,C1,,#2,d,e,C2,,#3,f,g,C3,,#4,h,i,C4,,

我想将上述转换为多维数组,循环读取每行数据的值并创建我自己的 json。

所以我从下面的代码开始。这将导致我的行数和列数。

int rowCount = result.TrimEnd('#').Split('#').Count();
int colCount = result.TrimEnd('#').Split('#')[0].TrimEnd(',').Split(',').Length;

//Defining my object which I want to fill.
JObject myObject = new JObject();

下面我想循环遍历行和列,从每一行和每一列获取数据值

for (int row = o ; row <= rowCount; row++)
{
    for (int col = 0; col <= colCount; col++)
    {
       //So here I want to do something like:
       var rowValue = multiArray[row][col];

       //After getting the row value below is the logic to add to my object
       if(col == 0)
       {
            myObject.Add("first", rowValue);    
       }
       else if(col == colCount)
       {
            myObject.Add("last", rowValue);
       }
       else
       {
            myObject.Add(col, rowValue);
       }
    }
}

所以我的问题是如何在我的代码中创建多维数组“multiArray”。

我的 json 示例:

{
  "first": 1
  "1": a,
  "2": b,
  "last": C1
},
{
  "first": 2
  "1": c,
  "2": d,
  "last": C2
}

标签: c#

解决方案


以下代码创建并填充您的多维数组,但您的数据存在问题。由于额外的逗号,您的 json 看起来不像您的示例 json。

string myString = "1,a,b,C1,,#2,d,e,C2,,#3,f,g,C3,,#4,h,i,C4,,#".TrimEnd('#');

var rows = myString.Split('#');
var rowCount = rows.Length;
var columnCount = rows[0].Split(',').Length;

string[,] multiArray = new string[rowCount, columnCount];

for (int i = 0; i < rowCount; i ++)
{
    var values = rows[i].Split(',');
    for (int j = 0; j < columnCount && j < values.Length; j++)
    {
        multiArray[i,j] = values[j];
    }
}

我从中得到的结果是有一个 4x6 数组,每行只有 4 个值。


推荐阅读