C#中如何将好几个 datatable 的信息整合到一个datatable里?或许不是简单的合并!!在线等!!30分悬赏!

2024-10-31 18:19:39
有2个网友回答
网友(1):

class Program
{
static void Main(string[] args)
{ //建立课程内存表
DataTable table1 = new DataTable();
table1.Columns.Add("CourseCode", Type.GetType("System.String"));
table1.Columns.Add("CourseName", Type.GetType("System.String"));
table1.Rows.Add(new object[2] { "A", "语文" });
table1.Rows.Add(new object[2] { "B", "数学" });
table1.Rows.Add(new object[2] { "C", "英语" });
ShowTable(table1);
//建立学生内存表
DataTable table2 = new DataTable();
table2.Columns.Add("StudentCode", Type.GetType("System.String"));
table2.Columns.Add("StudentName", Type.GetType("System.String"));
table2.Rows.Add(new object[2]{"1","张三"});
table2.Rows.Add(new object[2] { "2", "李四" });
table2.Rows.Add(new object[2] { "3", "王五" });
ShowTable(table2);
//建立学生成绩表
DataTable table4 = new DataTable();
table4.Columns.Add("StudentCode", Type.GetType("System.String"));
table4.Columns.Add("CourseCode", Type.GetType("System.String"));
table4.Columns.Add("Grade", Type.GetType("System.Int32"));
table4.Rows.Add(new object[3] { "1", "A", 78 });
table4.Rows.Add(new object[3] { "1", "B", 90 });
table4.Rows.Add(new object[3] { "1", "C", 67 });
table4.Rows.Add(new object[3] { "2", "B", 78 });
table4.Rows.Add(new object[3] { "2", "C", 90 });
table4.Rows.Add(new object[3] { "3", "A", 88 });
table4.Rows.Add(new object[3] { "3", "C", 67 });
ShowTable(table4);
//最终统计表
DataTable table5 = new DataTable();
DataColumn col = table5.Columns.Add("StudentCode", Type.GetType("System.String"));
table5.Columns.Add("StudentName", Type.GetType("System.String"));
foreach (DataRow r in table1.Rows)
{
table5.Columns.Add(r["CourseCode"].ToString(), Type.GetType("System.Int32"));
}
table5.PrimaryKey =new DataColumn[1]{table5.Columns[0]};
table2.PrimaryKey = new DataColumn[1] { table2.Columns[0] };
foreach (DataRow row in table4.Rows)
{
DataRow dRow = table5.Rows.Find(row["StudentCode"]);
if (dRow == null)
{
dRow = table5.NewRow();
dRow["StudentCode"] = row["StudentCode"];
DataRow fRow = table2.Rows.Find(row["StudentCode"]);
dRow["StudentName"] = (fRow != null) ? fRow["StudentName"] : null;
table5.Rows.Add(dRow);
}
dRow[row["CourseCode"].ToString()] = row["Grade"];
table5.AcceptChanges();
}
ShowTable(table5);
Console.ReadLine();
}
static void ShowTable(DataTable table)
{
Console.WriteLine(table.TableName);
Console.Write("\t");
foreach (DataColumn col in table.Columns)
{
Console.Write(string.Format("{0},", col.ColumnName));
}
Console.WriteLine();
foreach (DataRow row in table.Rows)
{
Console.Write("\t");
foreach (DataColumn col in table.Columns)
{
Console.Write(string.Format("{0},", row[col.ColumnName]));
}
Console.WriteLine();
}
}
}

//运行结果

CourseCode,CourseName,
A,语文,
B,数学,
C,英语,
StudentCode,StudentName,
1,张三,
2,李四,
3,王五,
StudentCode,CourseCode,Grade,
1,A,78,
1,B,90,
1,C,67,
2,B,78,
2,C,90,
3,A,88,
3,C,67,
StudentCode,StudentName,A,B,C,
1,张三,78,90,67,
2,李四,,78,90,
3,王五,88,,67,

网友(2):

你直接查出数据库几张表数据存在 一个DataTable不就ok了吗