加入数据表以通过LINQ获得新的数据表

问题描述:

我有一个名为datatable的数据表,其中包含具有ID,名字,姓氏列的数据.另一个数据表包含代码列userID1userID2userID3,工作.

I've a datatable named which contains data with a column of ID, firstname, lastname. Another datatable contains columns of code, userID1, userID2, userID3, work.

现在我想要一个新的数据表,其中应该包含两个数据表的列以及正确的数据.

Now i want a new datatable which should contain the column of both the datatable with proper data.

新数据表应包含以下数据:IDuserfullname1userfullname2userfullname3,工作.

New datatable should contain data as: ID, userfullname1, userfullname2, userfullname3, work.

在这里,我们通过datatable1的名字,姓氏和名字获取userfullname1的值. datatable2userID1.同样,我们通过名字, datatable1 的姓氏获得userfullname2的值, datatable2 中的userID2等等.

Here we get the value of userfullname1 by firstname, lastname of datatable1 & userID1 of datatable2. Similarly we get the value of userfullname2 by firstname, lastname of datatable1 & userID2 of datatable2 & so on.

Datatable1 中的ID值与 Datatable2 中的userID1userID2userID3相同.

最后,我想获得一个新的数据表,其代码为userfullname1,userfullname2,userfullname3,work.但是用户ID在datatable1中.因此,我想通过两个表中都存在的ID将Datatable1的名称绑定到Datatable2的所有3个用户ID.

Finally, i want to obtain a new datatable with code, userfullname1, userfullname2, userfullname3, work. But users IDs are in datatable1. So, i want to bind the names of Datatable1 to the all 3 userids of Datatable2 via their IDs whichare present in both the tables.

Datatable1:

Datatable1 :

iD  name
1    b
2    d
3    f
4    s

....

Datatable2:

Datatable2 :

   Code        userid1    userid2      userid3  work
    1f           1           3           6       gg
    2g           1           4           7       gg
    3b           3           4           7       gg
    4v           4           3           8       gg

新数据表:

Code    username1   username2   username3  work
1f           a           b           c       gg
2g           d           f           r       gg
3b           c           h           g       gg
4v           d           s           h       gg

我如何加入&获取新的数据表?

How can i join & get the new datatable ?

如果只希望生成的表具有名称和ID,则应这样做:

If you just want your resulting table to have name and id, you should do it like this:

DataTable dtResult = new DataTable();
dtResult.Columns.Add("ID", typeof(string));
dtResult.Columns.Add("name", typeof(string));


var result = from datatable1 in table1.AsEnumerable()
             join datatable2 in table2.AsEnumerable()
             on datatable1.Field<string>("ID") equals datatable2.Field<string>("userID")

             select dtResult.LoadDataRow(new object[]
             {
                datatable1.Field<string>("ID"),               
        string.Format("{0} {1}" ,datatable1.Field<string>("fname") ,datatable1.Field<string>("lname")),

              }, false);
result.CopyToDataTable();