2 回答

TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超2個贊
在我看來,您事先并不知道文件的行數(shù),并且在拆分行時也不知道項(xiàng)目的數(shù)量。在這種情況下,我不會使用固定矩陣,而是使用字典等。
static void Main(string[] args)
{
Dictionary<int, string[]> filesData = new Dictionary<int, string[]>();
importFiles(filesData);
}
static void importFiles(Dictionary<int, string[]> filesData)
{
var path = @"export/file.txt";
if (File.Exists(path))
{
string[] fileLines = File.ReadAllLines(path);
for (int i = 0; i < fileLines.Length; i++)
{
string line = fileLines[i];
string[] split = line.Split(';');
for (int j = 0; j < split.Length; j++)
{
split[j] = split[j].Trim();
}
int index = filesData.Count == 0 ? 0: filesData.Keys.Max();
filesData.Add(index + 1, split);
}
}
}

TA貢獻(xiàn)1865條經(jīng)驗(yàn) 獲得超7個贊
如果矩陣中的行數(shù)與讀取的行數(shù)不同(例如拋出異常),您可以在代碼中處理情況:
static void importFiles(string[,] matrix)
{
var path = @"export/file.txt";
if (!File.Exists(path)) return;
string[] fileLines = File.ReadAllLines(path);
if(fileLines.Length != matrix.GetLength(0))
// here you have couple of opitions
// throw new ArgumentException("Number of rows in passed matrix is different from number of lines in a file!");
// or just do nothing:
return;
string[,] map = new string[fileLines.Length, fileLines[0].Split(';').Length];
for (int i = start; i < fileLines.Length; i++)
{
string line = fileLines[i];
for (int j = 0; j < matrix.GetLength(1); j++)
{
string[] split = line.Split(';');
matrix[i, j] = split[j]?.Trim();
}
}
}
或者你可以matrix在你的方法中初始化你的數(shù)組:
string[] fileLines = File.ReadAllLines(path);
// c is number of columns, that you are using now
string[,] matrix = new string[fileLines.Length, c];
- 2 回答
- 0 關(guān)注
- 156 瀏覽
添加回答
舉報(bào)