查找表中数据的最大值和平均值

时间:2017-03-04 13:22:59

标签: c# visual-studio max average min

嗨所以我需要一些帮助来找到速度的最小值,最大值和平均值。我已经使用了数据网格视图并生成了包含速度的差异列。当用户使用数字加载文件时,速度被转换为双倍,并在表格中显示,例如之前:299之后:29.9。我想要做的是找到不同速度的平均值,即最小值和最大值。下面是一段代码片段,试图计算平均最小值和最大值,但它不起作用并且不断出现错误。

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);
                }

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

1 个答案:

答案 0 :(得分:1)

如果您的列包含浮点值,例如 29.9 ,那么使用转换为Integer会导致上述错误。如果您的单元格包含空格或其他不能被视为整数的值,也会发生这种情况。阅读专栏时需要更仔细的方法。

此外,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的无效输入 如果您的单元格内容的格式与您的区域设置相对应,则会删除无效格式错误。