将数据从CSV读取到数组(C#) [英] Reading data from a CSV to an array of arrays (C#)
问题描述
我已经打开了CSV文件,但是我不知道如何将结果数组从将行拆分为另一个数组中放入.目前,我有以下代码,希望它能对我的意思有更多的了解:
I have the CSV file opened, but I can't figure out how to put the resultant array from splitting the line into another array. I have the following code currently, hopefully it gives more of an idea of what I'm meaning:
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++;
}
}
有什么想法吗?我遇到两个错误:一个是说Cannot implicitly convert type 'string[]' to 'string'
,另一个是说Use of unassigned local variable 'FP_GamesArray'
.
Any ideas? I get two errors: One saying Cannot implicitly convert type 'string[]' to 'string'
and second saying Use of unassigned local variable 'FP_GamesArray'
.
推荐答案
您需要初始化数组,然后才能知道其中有多少行.
You need to initialize your array, to do that you need to know how many lines in there.
您可以执行以下操作,而不是逐行阅读:
Instead of reading line by line you can do:
string[][] FP_GamesArray = File.ReadLines("path")
.Select(line => line.Split(','))
.ToArray();
或者,也可以从List<string[]>
开始,使用它的add方法,然后在读取完成后将其转换为数组,如下所示:
Or altenatively, you can start with a List<string[]>
, use it's add method, then convert it to an array after the reading is finished, like below:
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();
这篇关于将数据从CSV读取到数组(C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!