我想在包含三个不同数据表的数据表上使用内部联接,并使用c#将结果作为合并数据表返回

时间:2019-02-25 13:58:58

标签: c# linq

表1:父级{列:ParentId,名称}

表2:Child {列:ChildId,ChildName}

表3:关系{列:RelationshipId,PrimaryId(ParentId),SecondaryId(子ID)}

1 个答案:

答案 0 :(得分:0)

尝试以下操作:

           DataTable parentTable = new DataTable();
           parentTable.Columns.Add("ParentId", typeof(string));
           parentTable.Columns.Add("Name", typeof(string));

           DataTable childTable = new DataTable();
           childTable.Columns.Add("ParentId", typeof(string));
           childTable.Columns.Add("ChildNameName", typeof(string));

           DataTable relationshipTable = new DataTable();
           relationshipTable.Columns.Add("RelationshipId", typeof(string));
           relationshipTable.Columns.Add("PrimaryId", typeof(string));
           relationshipTable.Columns.Add("SecondaryId", typeof(string));

           var results = (from r in relationshipTable.AsEnumerable()
                          join p in parentTable.AsEnumerable() on r.Field<string>("PrimaryId") equals p.Field<string>("ParentId")
                          join c in childTable.AsEnumerable() on r.Field<string>("SecondaryId") equals c.Field<string>("ChildID")
                          select new { r = r, p = p, c = c })
                         .ToList();