static void Main(string[] args)
{
//建立2个表,并填充数据
DataTable dt1 = new DataTable();
dt1.TableName = "dt1";
dt1.Columns.Add(new DataColumn("id",typeof(string)));
dt1.Columns.Add(new DataColumn("name", typeof(string)));
dt1.Rows.Add(new object[] {"001","叶杨" });
dt1.Rows.Add(new object[] { "002", "韩屏非" });
DataTable dt2 = new DataTable();
dt2.TableName = "dt2";
dt2.Columns.Add(new DataColumn("id", typeof(string)));
dt2.Columns.Add(new DataColumn("name", typeof(string)));
dt2.Columns.Add(new DataColumn("base_id", typeof(string)));
dt2.Rows.Add(new object[] { "001001", "语文" ,"001"});
dt2.Rows.Add(new object[] { "002001", "数学" ,"002"});
DataSet ds = new DataSet();
ds.Tables.Add(dt1);
ds.Tables.Add(dt2);
//建立关联关系
DataRelation r = new DataRelation("r1",ds.Tables["dt1"].Columns["id"],ds.Tables["dt2"].Columns["base_id"]);
ds.Relations.Add(r);
//从主表中的行索引到从表中的行
foreach (DataRow row in dt1.Rows)
{
DataRow[] childRows = row.GetChildRows(ds.Relations["r1"]);
System.Console.WriteLine(childRows.Length.ToString());
System.Console.WriteLine(childRows[0]["name"]);
}
//从从表中的行索引到主表中的行
foreach (DataRow row in dt2.Rows)
{
DataRow parentRow = row.GetParentRow(ds.Relations["r1"]);
System.Console.WriteLine(parentRow["name"]);
}
System.Console.Read();
}
在内存中处理2张表的数据关联运算
最新推荐文章于 2021-11-15 17:07:34 发布