gpt4 book ai didi

ado.net - 如何 : Use DataRelation to perform a join on two DataTables in a DataSet?

转载 作者:行者123 更新时间:2023-12-02 00:46:34 26 4
gpt4 key购买 nike

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

我在两个表之间创建了一个数据关系……然后呢?

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

有更好的方法吗?

最佳答案

看看这是否有帮助

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"]);
}
}

关于ado.net - 如何 : Use DataRelation to perform a join on two DataTables in a DataSet?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/331265/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com