【发布时间】:2017-01-24 10:11:16
【问题描述】:
我打算得到一个每列平均值的数组。
但由于 FormatException,我的应用程序在 sum[j] += int.Parse(csvArray[i,j]); 崩溃。我曾尝试使用 Convert.ToDouble 和 Double.Parse 但它仍然会引发该异常。
for loop 中的增量从 1 开始,因为 CSV 数组的 Row 0 and Column 0 是 字符串(名称和时间戳)。对于divisor 或total count of the fields that have values per column,我只计算not BLANK 的字段,因此是IF 语句。我想我需要帮助来处理异常。
以下是我现有的获取平均值的方法。
public void getColumnAverages(string filePath)
{
int col = colCount(filePath);
int row = rowCount(filePath);
string[,] csvArray = csvToArray(filePath);
int[] count = new int[col];
int[] sum = new int[col];
double[] average = new double[col];
for (int i = 1; i < row; i++)
{
for (int j = 1; j < col; j++)
{
if (csvArray[i,j] != " ")
{
sum[j] += int.Parse(csvArray[i,j]);
count[j]++;
}
}
}
for (int i = 0; i < average.Length; i++)
{
average[i] = (sum[i] + 0.0) / count[i];
}
foreach(double d in average)
{
System.Diagnostics.Debug.Write(d);
}
}
}
我已经上传了我在测试原型时使用的CSV file。它在某些列上有BLANK 值。我现有的 IF 语句 无法处理这种情况吗?
还有像1.324556-e09这样的条目,因为我认为是小数位数。我想我必须在csvToArray(filePath) 方法中修剪它,还是有其他有效的方法?谢谢一百万!
【问题讨论】:
-
那么
csvArray[i,j]失败时的值是多少? -
这是因为无法将字符串解析为整数,请在
csvArray中包含由csvToArray填充的示例数据 -
我还建议用
if(!string.IsNullOrWhitespace(csvArray[i,j]))检查空白,如果它根本不是有效数字,你可以使用int.TryParse来处理 -
@musefan 嗨,我添加了一个屏幕截图。谢谢!
-
@un-lucky 我已经手动检查过了,csvArray[1,1] 的值是“23313”。我不确定为什么它不解析。
标签: c# .net arrays csv multidimensional-array