我很难从我的CSV文件数据“智能眼data.csv”创建二维数组“智能数据”。我一直收到错误,说明“对象引用没有设置为对象的实例”。
我知道2 for循环对于创建矩阵的外部和内部维度是必要的,但仍然没有做到这一点。CSV数据只是一个数字电子表格。任何帮助都将不胜感激。谢谢
using (StreamReader oStreamReader = new StreamReader(File.OpenRead("Smart Eye data.csv")))
{
sFileContents = oStreamReader.ReadToEnd();
}
string[][] smartdata = new string[1000][];
string[] sFileLines = sFileContents.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
int i = 0;
foreach(string sFileline in sFileLines)
{
string[] rowarray = sFileline.Split(",".ToCharArray(),StringSplitOptions.RemoveEmptyEntries);
for (int j = 0; j < rowarray.Length; j++)
{
smartdata[i][j] =rowarray[j]; //where the error occurs
//Debug.Log(smartdata[i][j]);
}
i = i + 1 ;
}发布于 2019-01-04 01:05:31
您应该初始化2d数组的子数组:
foreach(string sFileline in sFileLines)
{
string[] rowarray = sFileline.Split(",".ToCharArray(),StringSplitOptions.RemoveEmptyEntries);
smartdata[i]=new string[rowarray.Length];
for (int j = 0; j < rowarray.Length; j++)
{
smartdata[i][j] =rowarray[j]; //where the error occurs
//Debug.Log(smartdata[i][j]);
}
i = i + 1 ;
}发布于 2019-01-04 00:12:04
如果您坚持使用2d数组(我不会),您只需要(并且坚持不使用csvhelper)。
foreach(string sFileline in sFileLines)
{
smartdata[i] = sFileline.Split(",".ToCharArray(),StringSplitOptions.RemoveEmptyEntries);
}如果你想用困难的方式做这件事,那就这样做。
for (int j = 0; j < rowarray.Length; j++)
{
smartdata[i] = new string[rowarray.Length];
smartdata[i][j] =rowarray[j]; //where the error occurs
//Debug.Log(smartdata[i][j]);
}
i = i + 1 ;现在你可以看到我最初的评论是什么意思了。I‘你必须分配每一行.
发布于 2019-01-04 00:25:08
pm100给了您真正的问题:您没有分配内部数组;因此出现了错误。
使用CSV库并不是个坏主意--但肯定不是必要的。
使用列表(而不是数组)的好处是不需要预先知道#/行或#/列。
下面是一个例子:
List<List<string>> mylist = new List<List<string>>();
using (StreamReader sr = new StreamReader(File.OpenRead("Smart Eye data.csv")))
{
string line;
while((line = sr.ReadLine()) != null)
{
System.Console.WriteLine(line);
List<string>row = line.Split(",").ToList();
mylist.Add(row);
}
}
...https://stackoverflow.com/questions/54031501
复制相似问题