alexhall9999
alexhall9999

Reputation: 1

datagridView rolling average values

I making some software that will calculate averages for the contents of a datagrid, the below code works perfectly, however im looking to only calculate an average for the first, second and third, 30 rows of data. To do this, I would need to specify the row.count, is this possible?

Here is my code:

for (int i = 0; i < dataGridView1.Rows.Count - 1; ++i) {
    sum +=Convert.ToDouble(dataGridView1.Rows[i].Cells["heartrate"].Value);
}

Upvotes: 0

Views: 1044

Answers (1)

leAthlon
leAthlon

Reputation: 744

So you want to make Row.Count in your loop variable?

  private double average(int firstRow,int RowsCount)
  { 
      double sum=0d;
      for (int i = firstRow; i < RowsCount; i++) 
      {
          for(int ii=0;ii<dataGridView1.Columns.Count;ii++)
          {
          sum +=Convert.ToDouble(dataGridView1[i,ii].Value);
          }
      }
      return sum/(RowsCount*dataGridView1[i].Columns.Count);
  } 

that like? or did I got it wrong? (sorry can't comment yet.)

EDIT:

if you like it shorter, you could try lambda of course:

 private double average(int startIDX ,int lng )
    {
        return dataGridView1.Rows.OfType<DataGridViewRow>().Where(x => x.Index >= startIDX && x.Index < startIDX + lng).Select(x => x.Cells.OfType<DataGridViewCell>().Sum(y => {try{return Convert.ToInt32(y.Value);}catch{return 0;}})).Average();
    }

this for example returns the average of all rows between Rows[startIDX] and Rows[startIDX+lng] . Here I'm using "int" as Type of the Cell's Value... Tell me your prefered Type and I'd help you better maybe...

Upvotes: 0

Related Questions