[英]Why does not work return C#?
我有以下代码:
public static Array readCVS(string absolutePath)
{
string[,] temperatureMatrix = new string[384, 288];
string value;
using (TextReader fileReader = File.OpenText(absolutePath))
{
var csv = new CsvReader(fileReader);
csv.Configuration.HasHeaderRecord = false;
int y = 1;
while (csv.Read())
{
for (int x = 1; csv.TryGetField<string>(x, out value); x++)
{
x = x - 1;
temperatureMatrix[1, 1] = value;
}
y = y + 1;
}
return temperatureMatrix;
}
}
所以return t;
不起作用,我的意思是它不返回数组,我也尝试在这里设置断点,然后我看不到填充数组的结构
您的代码似乎在用于读取 CsvReader 提取的行的列值的 for 中进入了无限循环。
我认为您应该更改代码以删除 for 循环内 x 的递减(不清楚该行的原因,但肯定不允许 x 前进到输入行的下一列)。
最后,您应该正确使用 y(对于行)和 x(对于列)来设置矩阵的值
public static Array readCVS(string absolutePath)
{
string[,] temperatureMatrix = new string[384, 288];
string value;
using (TextReader fileReader = File.OpenText(absolutePath))
{
var csv = new CsvReader(fileReader);
csv.Configuration.HasHeaderRecord = false;
int y = 0;
while (csv.Read())
{
for (int x = 0; csv.TryGetField<string>(x, out value); x++)
temperatureMatrix[x, y] = value;
y = y + 1;
}
return temperatureMatrix;
}
}
我还将 x 和 y 的初始索引从 1 更改为 0。 在 Net arrays(也是多维的)中,从索引 0 而不是 1 开始。
还请注意,此代码非常依赖于输入文件的确切结构。 如果您获得的文件超过 288 行或单行包含超过 384 个临时值,代码将崩溃并出现索引超出范围异常。
正如史蒂夫指出的那样,您的代码在很多地方似乎都不正确。 我还想指出一件事,最好使用List
而不是Array
,因为如果你有大文件,你会得到索引超出范围的异常。 List
会给你无限的长度。
public static List<string> readCVS(string absolutePath)
{
List<string> result = new List<string>();
string value;
using (TextReader fileReader = File.OpenText(absolutePath))
{
var csv = new CsvReader(fileReader);
csv.Configuration.HasHeaderRecord = false;
while (csv.Read())
{
for (int i = 0; csv.TryGetField<string>(i, out value); i++)
{
result.Add(value);
}
}
}
return result;
}
我不知道你为什么在你的代码中使用y
。 它没有用,我们只是在减少它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.