How To: Use DataRelation to perform a join on two DataTables in a DataSet?

限于喜欢 提交于 2019-11-28 12:46:30

See if this helps

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

DataTables support selection only on columns they own, joining many tables isn't supported.

I was finding the solution for the same problem. Well, I have given up and use SQL to do a join.

Someone has written some custom code to achieve joining DataTable. Maybe they are helpful for you: http://www.emmet-gray.com/Articles/DataTableJoins.htm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!