2017-03-04 180 views
0

嗨,所以我需要一些帮助找到速度的最小值,最大值和平均值。我已经使用了数据网格视图并生成了包括速度在内的差异列。当用户用数字加载文件时,速度转换为双倍,并在表中显示,例如,之前:299之后:29.9。我想要做的是找到不同速度的平均值,即最小值和最大值。下面是代码的一小部分,它试图解决avg min和max的问题​​,但它不起作用并且一直在引发一个错误。找到表中数据的最小最大值和平均值

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

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

+0

_keeps引发一个错误。怎么样才能分享那个错误信息? – Steve

+0

Soryy yes出现的错误是:mscorlib.dll中发生类型'System.FormatException'的未处理异常 附加信息:输入字符串格式不正确。 – 786

+0

额外的信息:我已经宣布MinSpeed,MaxSpeed和AvgSpeed全部为整数 – 786

回答

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无效输入。
如果您的单元格内容根据您的语言环境设置进行了格式设置,则这将删除无效的格式错误。

+0

我已经尝试了这个,但是又出现了一个错误:单词Cells以红色下划线。 错误\t CS1061 \t'DataGridViewRowCollection'不包含'Cells'的定义并且没有扩展方法可以找到接受类型'DataGridViewRowCollection'的第一个参数的'Cells'(是否缺少using指令或程序集引用?) – 786

+0

对不起,复制粘贴错误,将修复 – Steve

+0

我试过这个,但另一个错误已经出现,它似乎总是相同的行:if(double.TryParse(dataGridView1.Rows [x] .Cells [2] .Value,out值))和错误是:严重\t代码\t说明\t项目\t文件\t线\t抑制状态 错误\t CS1503 \t参数1:不能从“对象”转换为“字符串” – 786

相关问题