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 關注
- 113 瀏覽
添加回答
舉報