LEFT OUTER JOIN 2个数据表

时间:2012-05-01 19:20:25

标签: c# linq

我正在尝试了解如何查询,最好使用LINQ,2个数据表。 我想对他们进行LEFT OUTER JOIN

带有col的Datatable1:[ID] [colA]
带有col的DataTable2:[ID] [ColB] [ColC] ...

希望加入该ID。

有人可以给我看一个例子,以便我可以将它应用到我的数据表中吗?提前谢谢

3 个答案:

答案 0 :(得分:3)

根据给定的结果集编译并执行您期望的操作:

// 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"]};

答案 1 :(得分:2)

获得LEFT OUTER Join

你应该尝试使用@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}

<强>更新

鉴于您提供的内容,您应该查找LINQ-Dataset文章

以下是代码段

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);

答案 2 :(得分:0)

要获得内部联接,请尝试此

from x in Datatable1
join y in Datatable2 on x.ID equals y.ID
select new {x.colA, y.ColB, y.ColC }