Reputation: 7
Hi so i need some help finding the min, max and average of speed. I have made used a data grid view and produced difference columns including speed. When the user loads the file with the numbers the speed is converted to a double with is displayed in the table e.g. before: 299 after: 29.9. What i'm trying to do is find the average of the different speeds the min and max. Here is a snippet of the code that is trying the work out the avg min and max however it doesnt work and keeps bringing up an error.
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);
}
Apologies for my code its not in the best format. Any help would be appreciated
Upvotes: 0
Views: 255
Reputation: 216293
If your column contains floating point values like 29.9 then using the conversion to Integer results in the mentioned error. This happens also if your cells contain blanks or other values that cannot be considered integer numbers. You need a more careful approach when reading your column.
Also, Linq is wonderful for many tasks, but sometimes you should take in consideration that using it without looking at the big picture is a performance killer. In your current code there are three loops over the grid rows, one explicit, two hidden in the linq syntax, and all three loops, are reading the same cell value.
I should measure before talking about performances, but I think it is a safe bet to say that your code will be faster using a normal for loop.
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;
I have used double.TryParse to avoid invalid inputs from your gridview.
This will remove the invalid format error if the content of your cells are formatted accordingly to your locale settings.
Upvotes: 1