Code
/// <summary>
/// 对DataTable进行GroupBy操作
/// </summary>
/// <param name="p_table"></param>
/// <param name="p_key"></param>
/// <returns></returns>
private static DataTable GetTableByGroupBy(DataTable p_table, string p_key, string p_colname)
{
//对DataTable进行Group by
DataTable parTable = new DataTable();
DataColumn key = new DataColumn();
key.DataType = System.Type.GetType("System.String");
key.ColumnName = "MC";
parTable.Columns.Add(key);
DataColumn avg = new DataColumn();
avg.DataType = System.Type.GetType("System.Double");
avg.ColumnName = "AVG";
parTable.Columns.Add(avg);
foreach (DataRow row in p_table.Rows)
{
if (parTable.Select(string.Format("mc='{0}'", row[p_key].ToString())).Length == 0)
{
parTable.Rows.Add(new object[] { row[p_key] })["mc"] = row[p_key].ToString();
}
}
DataSet ds = new DataSet();
DataTable childTable = p_table.Copy();
childTable.TableName = "child";
ds.Tables.Add(childTable);
parTable.TableName = "par";
ds.Tables.Add(parTable);
ds.Relations.Add("partochild", parTable.Columns["mc"], childTable.Columns[p_key]);
parTable.Columns["avg"].Expression = string.Format("avg(child(partochild).{0})", p_colname);
return parTable;
}
/// <summary>
/// 对DataTable进行GroupBy操作
/// </summary>
/// <param name="p_table"></param>
/// <param name="p_key"></param>
/// <returns></returns>
private static DataTable GetTableByGroupBy(DataTable p_table, string p_key, string p_colname)
{
//对DataTable进行Group by
DataTable parTable = new DataTable();
DataColumn key = new DataColumn();
key.DataType = System.Type.GetType("System.String");
key.ColumnName = "MC";
parTable.Columns.Add(key);
DataColumn avg = new DataColumn();
avg.DataType = System.Type.GetType("System.Double");
avg.ColumnName = "AVG";
parTable.Columns.Add(avg);
foreach (DataRow row in p_table.Rows)
{
if (parTable.Select(string.Format("mc='{0}'", row[p_key].ToString())).Length == 0)
{
parTable.Rows.Add(new object[] { row[p_key] })["mc"] = row[p_key].ToString();
}
}
DataSet ds = new DataSet();
DataTable childTable = p_table.Copy();
childTable.TableName = "child";
ds.Tables.Add(childTable);
parTable.TableName = "par";
ds.Tables.Add(parTable);
ds.Relations.Add("partochild", parTable.Columns["mc"], childTable.Columns[p_key]);
parTable.Columns["avg"].Expression = string.Format("avg(child(partochild).{0})", p_colname);
return parTable;
}