简体   繁体   中英

how to add new row into by column name in datatable

I try to add new row to footer of column at calculated for Average of each cell in column.

Original datatable:

 col1 | col2 | col3 | ... | col20 |
------|------|------|-----|-------|
  5   |  10  |  5   | ... |   8   |
------|------|------|-----|-------|
  8   |   7  |  8   | ... |   2   |

And I would like to do below:

  col1 | col2 | col3 | ... | col20 |
 ------|------|------|-----|-------|
   5   |  10  |  5   | ... |   8   |
 ------|------|------|-----|-------|
   8   |   7  |  8   | ... |   2   |
-------|------|------|-----|-------|
  6.5  |  8.5 | 6.5  | ... |   5   |

Here's my code:

    if(sum[i] == 0 )
    {
       dt.Columns.Remove("BIN"+i.ToString()+"");
    }
    else
    {
       dt.Columns.Add("%BIN"+i.ToString()+"", typeof(decimal),"(BIN"+i.ToString()+" / 
       [In System])*100");
       if (i == 1)
       {
         dt.Columns.Add("100-%BIN1", typeof(double), "100 -[%BIN1]");
         Avg[i] = Convert.ToDouble(dt.Compute("Avg([col"+i.Tostring()+"])", string.Empty));
       }
       else
       {
         Avg[i] = Convert.ToDouble(dt.Compute("Avg([col" + i.ToString() + "])", string.Empty)); 
       }
       dt.Rows.Add("Avg_xbar"+i.ToString()+"", Avg[i]);
   }

From my code above,There is a problem about result is below:

    col1   | col2 | col3 | ... | col20 |
-----------|------|------|-----|-------|
     5     |  10  |  5   | ... |   8   |
-----------|------|------|-----|-------|
    8      |   7  |  8   | ... |   2   |
-----------|------|------|-----|-------|
Avg_xbar1  | 6.5  |      |     |       |
-----------|------|------|-----|-------|
Avg_xbar2  | 8.5  |      |     |       |
-----------|------|------|-----|-------|
Avg_xbar3  | 6.5  |      |     |       |
-----------|------|------|-----|-------|
   ...     | ...  |      |     |       |
-----------|------|------|-----|-------|
Avg_xbar20 |  5   |      |     |       |

I'm assuming that you've got that code running in a loop for each column. You'll want to move the addition of rows outside of this loop.

for (var i = 0; i < columns.length; i++) {
  // existing looping logic
}
dt.Rows.Add(Avg);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM