[英]LEFT OUTER JOIN 2 datatables
I'm trying to understand how to query, preferably with LINQ, 2 datatables. 我试图了解如何查询,最好使用LINQ 2个数据表。 I would like to do a LEFT OUTER JOIN on them
我想对他们做一个左外连接
Datatable1 with col's: [ID] [colA] 带有col的Datatable1:[ID] [colA]
DataTable2 with col's: [ID] [ColB] [ColC] ... 具有col的DataTable2:[ID] [ColB] [ColC] ...
Looking to join on that ID. 希望加入该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
获得
LEFT OUTER Join
and you should try using @Joanna link. 并且您应该尝试使用@Joanna链接。
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 UPDATE
Given what you provide you should look for LINQ-Dataset articles 根据您提供的内容,您应该查找LINQ-Dataset文章
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 }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.