Solved

Linq - join 2 datatables

Posted on 2008-06-25
5
3,818 Views
Last Modified: 2013-11-26
I'm learning LINQ. But I'm already stuck. (the codebehind may be c# or vb.net - I know them both)
I have 2 datatables like below and I want to create the third table using LINQ.
The key of both is ID. I want to join the two datatables so that I have all the records of the first table (left join).
Can someone help me figure this out.


FirstDataTable - Table 1
 ID      Type            Col1            Col2            
----      ---------                           --------                           ---------
2      Blue            XYZ            ABC
4      Green            LMN            CDF
1      Orange            OPE            BGD
 
Second Table: Table2
 ID      Part            Quantity      
----      ---------                          ---------
1      425687            10
2      425659            25
3      395678            30
4      426589            50
5      423568            25
 
Desired result (in a dataTable if it's possible)
 ID      Type              Part            Quantity            
----      ---------      ---------      ---------
1      Orange            425687            10
2      Blue            425659            25
4      Green            426589            50
0
Comment
Question by:Dhaest
  • 3
  • 2
5 Comments
 
LVL 21

Accepted Solution

by:
naspinski earned 500 total points
ID: 21863470
This is assuming your 2 datatables are dt1 and dt2
// get the rows you want and combine them into logical rows here:
var combinedRows = from p1 in dt1.AsEnumerable() join p2 in dt2.AsEnumerable() on p1["ID"] equals p2["ID"] orderby p1["ID"] select new { p1,p2 };
 
// now make the new datatable
DataTable dt = new DataTable();
DataColumn dcId = new DataColumn("ID", typeof(int));
DataColumn dcType = new DataColumn("Type", typeof(string));
DataColumn dcPart = new DataColumn("Part", typeof(int));
DataColumn dcQuantity = new DataColumn("Quantity", typeof(int));
dt.Columns.Add(dcId);
dt.Columns.Add(dcType);
dt.Columns.Add(dcPart);
dt.Columns.Add(dcQuantity);
//table is made, now just take and insert your values into the new DataTable
 
foreach (var v in combinedRows)
{
    DataRow dr = dt.NewRow();
    dr["ID"] = v.p1["ID"];//this is in v.p1
    dr["Type"] = v.p1["Type"];
    dr["Part"] = v.p2["Part"];//notice we are looking in v.p2 here now
    dr["Quantity"] = v.p2["Quantity"];
    dt.Rows.Add(dr);
}
 
//now put it on the screent o make sure it worked
GridView gv = new GridView();
gv.DataSource = dt;
gv.DataBind();
form1.Controls.Add(gv);

Open in new window

0
 
LVL 53

Author Comment

by:Dhaest
ID: 21863525
So easy (just use the join directly, how could I overlook it). Thanks anyway.
For c# I found this link: http://msdn.microsoft.com/en-us/library/bb397676.aspx
0
 
LVL 21

Expert Comment

by:naspinski
ID: 21863568
the more I learn about linq, the easier everything seems :)
0
 
LVL 53

Author Comment

by:Dhaest
ID: 21863629
Do you know how I need to do this statement in vb.net ? I can't figure out the last part: select ...

Dim combinedRows = From p1 In FirstTable.AsEnumerable() Join p2 In secondTable.AsEnumerable On FirstTable("id") Equals secondTable("id") Order By FirstTable("id") Select New p1
0
 
LVL 21

Expert Comment

by:naspinski
ID: 21863664
if you are just selecting p1, you can just do this:

Dim combinedRows = From p1 In FirstTable.AsEnumerable() Join p2 In secondTable.AsEnumerable() On FirstTable("id") Equals secondTable("id") Order By FirstTable("id") Select p1

but if you are looking for the same way to do "Select new {something, sometheing_else}" it isn't that easy in VB, you have to aggregate yourself:
http://www.infoq.com/news/2007/09/LINQ-Aggregates
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
SQL Login 17 50
How to prevent website from publishing with errors 9 47
Search an image for an image 3 30
Calculate number of nights between two dates 5 24
Flash (http://en.wikipedia.org/wiki/Adobe_Flash) has evolved over the years to where it has become a masterful tool for displaying content screen.  It has excellent layout placement, UI precision as well as rendering capabilities. This, along with t…
In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
In a recent question (https://www.experts-exchange.com/questions/28997919/Pagination-in-Adobe-Acrobat.html) here at Experts Exchange, a member asked how to add page numbers to a PDF file using Adobe Acrobat XI Pro. This short video Micro Tutorial sh…
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.

778 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question