【发布时间】:2014-07-23 17:36:03
【问题描述】:
我的应用程序中有 2 个数据表。第一个 DataTable 叫做Table1,看起来像这样
-------------------------------------
| Key | Column1 | Column2 | Foreign |
|-----------------------------------|
| 0 | dsfsfsd | sdfsrer | 1 |
|-----------------------------------|
| 1 | dertert | qweqweq | NULL |
|-----------------------------------|
| 2 | prwersd | xzcsdfw | 3 |
-------------------------------------
第二个叫做Table2,看起来像这样
----------------------------------------
| Key | Column3 | Column4 | Column5 |
|--------------------------------------|
| 1 | dsfsfsd | sdfsrer | fghfghg |
|--------------------------------------|
| 3 | prwersd | xzcsdfw | nbmkuyy |
----------------------------------------
所以我想使用 LINQ 对这两个表进行内部连接,以便连接的表看起来像这样。如果链接到 Table2 的外键为 NULL,我不想丢失来自 Table1 的数据
---------------------------------------------------------
| 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 |
---------------------------------------------------------
这是我尝试过的
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
}
但是,此 LINQ 查询会跳过不匹配的记录。我该怎么做才能得到上面的结果?
解决方案:所以 C.J. 的回答为我指明了正确的方向。我将查询更改为
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
}
但是,现在它抛出异常 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")
它奏效了。确保将COLUMN_TYPE 更新为该特定列的类型。 SelectedColumns中的对象也都是Nullable<>
【问题讨论】:
-
LEFT OUTER JOIN in LINQ 的可能重复项
-
this的可能重复