【发布时间】:2018-11-15 19:09:38
【问题描述】:
我有一个这样的逗号分隔字符串:
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
}
【问题讨论】:
-
在给定起始字符串
"1,a,b,C1,,#2,d,e,C2,,#3,f,g,C3,,#4,h,i,C4,,#" -
那么你卡在哪里了?
-
@MattBurland 我最终的 json 将取决于文件的行和列,即字符串。我会负责创建 json,只是我不知道在上面的代码中创建多数组“multiArray”,我可以从中循环。我已经用 json 更新了我的帖子。
-
@OleEHDufour 正如我的帖子中提到的,我不知道如何创建“多数组”以便循环遍历它。
-
@user1563677 - 你有一个示例输入,示例输出是什么?
标签: c#