I'm trying to understand how to query, preferably with LINQ, 2 datatables. I would like to do a LEFT OUTER JOIN on them
Datatable1 with col's: [ID] [colA]
DataTable2 with col's: [ID] [ColB] [ColC] ...
Looking to join on that ID.
Can someone please show me an example so I can apply it to the datatables I have? Thank you in advance
This compiles and does what you would expect based on the result set given:
// create the default row to be used when no value found
var defaultRow = DataTable2.NewRow();
defaultRow[0] = 0;
defaultRow[1] = String.Empty;
// the query
var result = from x in DataTable1.AsEnumerable()
join y in DataTable2.AsEnumerable() on (string)x["ID"] equals (string)y["ID"]
into DataGroup
from row in DataGroup.DefaultIfEmpty<DataRow>(defaultRow)
select new {a = x["ColA"], b = (string)row["ColB"]};
To get a LEFT OUTER Join
and you should try using @Joanna link.
from x in DataTable1
join y in DataTable2 on x.ID equals y.ID into DataGroup
from item in DataGroup.DefaultIfEmpty(new y.ColB = String.Empty , y.ColC = String.Empty})
select new {x.ColA, item.ColB , item.ColC}
UPDATE
Given what you provide you should look for LINQ-Dataset articles
Here is the code snippet
DataTable DataTable1 = new DataTable();
DataTable DataTable2 = new DataTable();
DataTable1.Columns.Add("ID");
DataTable1.Columns.Add("ColA");
DataTable1.Rows.Add(1, "A");
DataTable1.Rows.Add(2, "B");
DataTable2.Columns.Add("ID");
DataTable2.Columns.Add("ColB");
DataTable2.Rows.Add(1, "B");
var result = from x in DataTable1.AsEnumerable()
join y in DataTable2.AsEnumerable() on x["ID"] equals y["ID"] into DataGroup
from item in DataGroup.DefaultIfEmpty()
select new {
ID = x["ID"],
ColA = x["ColA"],
ColB = item == null ? string.Empty : item["ColB"]
};
foreach (var s in result)
Console.WriteLine("{0}", s);
To get an inner join try this
from x in Datatable1
join y in Datatable2 on x.ID equals y.ID
select new {x.colA, y.ColB, y.ColC }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.