Solved

Linq - join 2 datatables

Posted on 2008-06-25
5
3,811 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Summary Displaying images in RichTextBox is a common requirement with limited solutions available. Pasting through clipboard or embedding into RTF content only support static images.  This article describes how to insert Windows control objects int…
A basic question.. “What is the Garbage Collector?” The usual answer given back: “Garbage collector is a background thread run by the CLR for freeing up the memory space used by the objects which are no longer used by the program.” I wondered …
This is used to tweak the memory usage for your computer, it is used for servers more so than workstations but just be careful editing registry settings as it may cause irreversible results. I hold no responsibility for anything you do to the regist…
As a trusted technology advisor to your customers you are likely getting the daily question of, ‘should I put this in the cloud?’ As customer demands for cloud services increases, companies will see a shift from traditional buying patterns to new…

863 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now