我的应用程序中有 2 个数据表。第一个 DataTable 被调用Table1
,看起来像这样
-------------------------------------
| Key | Column1 | Column2 | Foreign |
|-----------------------------------|
| 0 | dsfsfsd | sdfsrer | 1 |
|-----------------------------------|
| 1 | dertert | qweqweq | NULL |
|-----------------------------------|
| 2 | prwersd | xzcsdfw | 3 |
-------------------------------------
Run Code Online (Sandbox Code Playgroud)
第二个被调用Table2
,看起来像这样
----------------------------------------
| Key | Column3 | Column4 | Column5 |
|--------------------------------------|
| 1 | dsfsfsd | sdfsrer | fghfghg |
|--------------------------------------|
| 3 | prwersd | xzcsdfw | nbmkuyy |
----------------------------------------
Run Code Online (Sandbox Code Playgroud)
所以我想使用 LINQ 对这两个表进行内部连接,以便连接的表看起来像这样。Table1
如果链接到的外键Table2
为 NULL ,我不想丢失数据
---------------------------------------------------------
| Key | Column1 | Column2 | Column3 | Column4 | Column5 |
|-------------------------------------------------------|
| 0 | dsfsfsd | sdfsrer | dsfsfsd | sdfsrer | fghfghg |
|-------------------------------------------------------|
| 1 | dertert | qweqweq | NULL | NULL | NULL | // This row is missing in my application
|-------------------------------------------------------|
| 2 | prwersd | xzcsdfw | prwersd | xzcsdfw | nbmkuyy |
---------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)
这是我尝试过的
var query = from table1Row in Table1.AsEnumerable()
join table2Row in Table2.AsEnumerable()
on table1Row.Foreign equals table2Row.Key
select new SelectedColumns
{
Column1 = table1Row.Column1
Column2 = table1Row.Column2
Column3 = table2Row.Column3
Column4 = table2Row.Column4
Column5 = table2Row.Column5
}
Run Code Online (Sandbox Code Playgroud)
但是,此 LINQ 查询会跳过不匹配的记录。我该怎么做才能得到上面的结果?
解决方案:所以 CJ 的回答为我指明了正确的方向。我将查询更改为
var query = from table1Row in Table1.AsEnumerable()
join table2Row in Table2.AsEnumerable()
on table1Row.Foreign equals table2Row.Key into leftJoin
from table2Row in leftJoin.DefaultIfEmpty()
select new SelectedColumns
{
Column1 = table1Row.Column1
Column2 = table1Row.Column2
Column3 = table2Row.Column3
Column4 = table2Row.Column4
Column5 = table2Row.Column5
}
Run Code Online (Sandbox Code Playgroud)
但是,现在它正在抛出异常Value cannot be null. Parameter name: row
。事实证明,当您选择想要的字段时,您需要使用布尔表达式来检查该值是否为 NULL。所以我将该部分更新为
Column1 = table1Row.Field<COLUMN_TYPE?>("COLUMN_TYPE")
Column2 = table1Row.Field<COLUMN_TYPE?>("Column2")
Column3 = table2Row == null ? (COLUMN_TYPE?)null : table2Row.Field<COLUMN_TYPE?>("Column3")
Column4 = table2Row == null ? (COLUMN_TYPE?)null : table2Row.Field<COLUMN_TYPE?>("Column4")
Column5 = table2Row == null ? (COLUMN_TYPE?)null : table2Row.Field<COLUMN_TYPE?>("Column5")
Run Code Online (Sandbox Code Playgroud)
它奏效了。确保更新COLUMN_TYPE
为该特定列的类型。里面的对象SelectedColumns
也都是Nullable<>
你需要使用Left Outer Join
在LINQ
请参考此页面:http : //msdn.microsoft.com/en-US/vstudio/ee908647.aspx#leftouterjoin