dan*_*tdj 0 c# csv arrays jagged-arrays
我打开了CSV文件,但我无法弄清楚如何将结果数组拆分成另一个数组.我目前有以下代码,希望它更能让我了解我的意思:
private void ReadFileToArray(StreamReader file)
{
int i = 0;
string[][] FP_GamesArray;
while (!file.EndOfStream)
{
string line = file.ReadLine();
if (!String.IsNullOrWhiteSpace(line))
{
string[] values = line.Split(',');
MessageBox.Show(values.ToString());
FP_GamesArray[i] = values;
}
i++;
}
}
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?我得到两个错误:一个说法Cannot implicitly convert type 'string[]' to 'string',第二个说Use of unassigned local variable 'FP_GamesArray'.
你需要初始化你的数组,为此你需要知道那里有多少行.
您可以执行以下操作,而不是逐行阅读:
string[][] FP_GamesArray = File.ReadLines("path")
.Select(line => line.Split(','))
.ToArray();
Run Code Online (Sandbox Code Playgroud)
或者说,你可以从a开始List<string[]>,使用它的add方法,然后在读完后将其转换为数组,如下所示:
List<string[]> lines = new List<string[]>();
while (!file.EndOfStream)
{
string line = file.ReadLine();
if (!String.IsNullOrWhiteSpace(line))
{
lines.Add(line.Split(',');
}
}
string[][] FP_GamesArray = lines.ToArray();
Run Code Online (Sandbox Code Playgroud)