2 回答

TA贡献1866条经验 获得超5个赞
这是您需要的:
string csvBoard = "0,1,0\n2,0,1\n0,0,1";
int[][] csvArray =
csvBoard
.Split('\n') // { "0,1,0", "2,0,1", "0,0,1" }
.Select(x =>
x
.Split(',') // { "X", "Y", "Z" }
.Select(y => int.Parse(y)) // { X, Y, Z }
.ToArray())
.ToArray();

TA贡献1895条经验 获得超7个赞
我猜这是某种家庭作业,所以我会尝试使用最基本的解决方案,这样老师就不知道了:)。
string csvBoard = "0,1,0\n2,0,1\n0,0,1";
// This splits the csv text into rows and each is a string
string[] rows = csvBoard.Split('\n');
// Need to alocate a array of the same size as your csv table
int[,] table = new int[3, 3];
// It will go over each row
for (int i = 0; i < rows.Length; i++)
{
// This will split the row on , and you will get string of columns
string[] columns = rows[i].Split(',');
for (int j = 0; j < columns.Length; j++)
{
//all is left is to set the value to it's location since the column contains string need to parse the values to integers
table[i, j] = int.Parse(columns[j]);
}
}
// For jagged array and some linq
var tableJagged = csvBoard.Split('\n')
.Select(row => row.Split(',')
.Select(column => int.Parse(column))
.ToArray())
.ToArray();
这是我关于如何改进它以便学习这些概念的建议。制作一个更适用的方法,无论大小如何,它都可以溢出任何随机 csv,并返回一个二维数组而不是锯齿状数组。当有人没有将有效的 csv 文本作为参数放入您的方法时,也尝试处理这种情况。
- 2 回答
- 0 关注
- 93 浏览
添加回答
举报