我想把我的价值放在:
结果|一个|两个| 3
平均值| 1.4 | 2.45 | 3
但我的结果却是:
结果|一个|两个| 3
平均值| 1.4
平均值| 2.45
平均值| 3
有没有办法改变它?我的代码在
之下private void button1_Click(object sender, EventArgs e)
{
DataTable dtGrid = gridData.DataSource as DataTable;
DataTable dtResult = new DataTable();
Math columnIndex = new Math();
dtResult.Columns.Add("Result", typeof(string));
dtResult.Columns.Add("One", typeof(double));
dtResult.Columns.Add("Two", typeof(double));
dtResult.Columns.Add("Three", typeof(double));
dtResult.Columns.Add("Four", typeof(double));
dtResult.Columns.Add("Five", typeof(double));
dtResult.Columns.Add("Six", typeof(double));
for (int i = 1; i < dtGrid.Columns.Count; i++)
{
List<double> avgList = new List<double>();
for (int j = 1; j < dtGrid.Rows.Count ; j++)
{
avgList.Add(Convert.ToDouble(dtGrid.Rows[j][i].ToString()));
}
double averageList = columnIndex.getAverageValue(avgList);
dtResult.Rows.Add("average", averageList);
gridData2.DataSource = dtResult;
}
}
答案 0 :(得分:1)
你在内循环(每列)的每次迭代中添加一个新行,这就是你得到意想不到的结果的原因;所以你需要做的是,在开始迭代之前创建一个新行,并将每列的avg添加到新创建的row.add在列迭代完成后将新行添加到列中;您可以将添加项目的逻辑更改为列表,如下所示:
DataRow dAvgRow = dtResult.NewRow();
DataRow dMinRow = dtResult.NewRow();
dAvgRow[0]="average";
dMinRow[0] = "Minimum";
for (int i = 1; i < dtGrid.Columns.Count; i++)
{
List<double> avgList = new List<double>();
for (int j = 1; j < dtGrid.Rows.Count; j++)
{
avgList.Add(Convert.ToDouble(dtGrid.Rows[j][i].ToString()));
}
double averageList = avgList.Average();
dAvgRow[i] = averageList.ToString("#.##");
dMinRow[i]=avgList.Min();
}
dtResult.Rows.Add(dAvgRow);
dtResult.Rows.Add(dMinRow);
gridData2.DataSource = dtResult;