如何:使用 DataRelation 对 DataSet 中的两个 DataTable 执行连接? [英] How To: Use DataRelation to perform a join on two DataTables in a DataSet?

查看:23
本文介绍了如何:使用 DataRelation 对 DataSet 中的两个 DataTable 执行连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在数据集中的两个数据表之间执行连接?

How do I perform a join between two DataTables in a Dataset?

我在两个表之间创建了一个 DataRelation……然后呢?

I created a DataRelation between two tables….then what?

我正在查看有关如何执行此操作的一种解释(http://www.emmet-gray.com/Articles/DataTableJoins.htm)这涉及将行从表复制到结果表?

I'm looking at one explanation on how to do it (http://www.emmet-gray.com/Articles/DataTableJoins.htm) which involves copying rows from tables to a result table?

有没有更好的方法来做到这一点?

Is there a better way to do this?

推荐答案

看看有没有帮助

DataTable person = new DataTable();
person.Columns.Add("Id");
person.Columns.Add("Name");

DataTable pet = new DataTable();
pet.Columns.Add("Id");
pet.Columns.Add("Name");
pet.Columns.Add("OwnerId");

DataSet ds = new DataSet();
ds.Tables.AddRange(new[] { person, pet });

ds.Relations.Add("PersonPet",person.Columns["Id"], pet.Columns["OwnerId"]);

DataRow p = person.NewRow();
p["Id"] = 1;
p["Name"] = "Peter";
person.Rows.Add(p);

p = person.NewRow();
p["Id"] = 2;
p["Name"] = "Alex";
person.Rows.Add(p);

p = pet.NewRow();
p["Id"] = 1;
p["Name"] = "Dog";
p["OwnerId"] = 1;
pet.Rows.Add(p);

p = pet.NewRow();
p["Id"] = 2;
p["Name"] = "Cat";
p["OwnerId"] = 2;
pet.Rows.Add(p);


foreach (DataRow personRow in person.Rows)
{
    Console.WriteLine("{0} - {1}",personRow["Id"], personRow["Name"]);
    foreach (DataRow petRow in personRow.GetChildRows("PersonPet"))
    {
        Console.WriteLine("{0} - {1}", petRow["Id"], petRow["Name"]);
    }
}

这篇关于如何:使用 DataRelation 对 DataSet 中的两个 DataTable 执行连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆