【问题标题】:finding the min max and average of data in a table查找表中数据的最小最大值和平均值
【发布时间】:2017-07-24 14:32:42
【问题描述】:

您好,所以我需要一些帮助来确定速度的最小值、最大值和平均值。我已经使用了数据网格视图并生成了包括速度在内的差异列。当用户加载带有数字的文件时,速度将转换为双倍,并显示在表格中,例如之前:299 之后:29.9。我想要做的是找到不同速度的最小值和最大值的平均值。这是尝试计算平均最小值和最大值的代码的 sn-p,但它不起作用并不断出现错误。

MinSpeed = dataGridView1.Rows.Cast<DataGridViewRow>()
                    .Min(r => Convert.ToInt32(r.Cells[2].Value));
                label10.Text = "Minimum Speed: " + MinSpeed;

                MaxSpeed = dataGridView1.Rows.Cast<DataGridViewRow>()
                    .Max(r => Convert.ToInt32(r.Cells[2].Value));
                label17.Text = "Maximum speed: " + MaxSpeed;

                AvgSpeed = 0;
                for (int i = 0; i < dataGridView1.Rows.Count; ++i)
                {
                    AvgSpeed += Convert.ToInt32(dataGridView1.Rows[i].Cells[2].Value);
                }

抱歉,我的代码格式不是最好的。任何帮助将不胜感激

【问题讨论】:

  • 不断出现错误。如何分享该错误消息?
  • 很抱歉,出现的错误是:mscorlib.dll 中出现“System.FormatException”类型的未处理异常附加信息:输入字符串的格式不正确。
  • 额外信息:我已将 MinSpeed、MaxSpeed 和 AvgSpeed 都声明为整数

标签: c# visual-studio max average min


【解决方案1】:

如果您的列包含像 29.9 这样的浮点值,则使用转换为整数会导致上述错误。如果您的单元格包含不能被视为整数的空白或其他值,也会发生这种情况。阅读您的专栏时,您需要更加谨慎。

此外,Linq 非常适合许多任务,但有时您应该考虑到使用它而不看全局是性能杀手。在您当前的代码中,网格行上有三个循环,一个显式循环,两个隐藏在 linq 语法中,并且所有三个循环都读取相同的单元格值。
我应该在谈论性能之前进行测量,但我认为可以肯定地说,使用普通的 for 循环您的代码会更快。

double minSpeed = double.MaxValue;
double maxSpeed = 0.0;
double sumSpeed = 0.0;
for(int x = 0; x < dataGridView1.Rows.Count; x++)
{
    double value;

    // If TryParse cannot convert the input it returns false and this
    // code will simply skip the row and continue with the next one.
    // Of course you can code an else condition and display an error
    // message referencing the invalid line (x)
    if(double.TryParse(dataGridView1.Rows[x].Cells[2].Value.ToString(), out value))
    {
        if(value < minSpeed) minSpeed = value;
        if(value > maxSpeed) maxSpeed = value;
        sumSpeed += value;
    }
}
double averageSpeed = sumSpeed / dataGridView1.Rows.Count;

我使用了 double.TryParse 来避免来自您的 gridview 的无效输入。
如果您的单元格内容根据您的区域设置进行格式化,这将消除无效格式错误。

【讨论】:

  • 我已经尝试过了,但出现了另一个错误:“单元格”一词带有红色下划线。错误 CS1061“DataGridViewRowCollection”不包含“Cells”的定义,并且找不到接受“DataGridViewRowCollection”类型的第一个参数的扩展方法“Cells”(您是否缺少 using 指令或程序集引用?)
  • 我已经尝试过了,但是又出现了另一个错误,而且它似乎总是在同一行:if(double.TryParse(dataGridView1.Rows[x].Cells[2].Value, out value )) 错误是:严重性代码描述项目文件行抑制状态错误CS1503参数1:无法从'object'转换为'string'
  • 在传递给 TryParse 的 cell.value 处添加了 ToString()
猜你喜欢
  • 2015-01-16
  • 1970-01-01
  • 2014-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-04
  • 2016-12-29
  • 2015-12-24
相关资源
最近更新 更多