当右侧为空时,Linq Left Join 在列表上失败
Linq Left Join Fails on List when right side is empty
我正在尝试对 2 个列表执行左联接,我 运行 遇到了查询问题,如果右列表为空,则左联接失败。如何更改查询,以便即使列表为空,左连接仍然有效
示例查询:
var received = new List<Foo>{new Foo{ProductId=1,WarehouseSectionId=2, qty= 7}};
var reserved = new List<Foo>{};
var leftOuterJoin = from r in received
join rs in reserved.DefaultIfEmpty()
on new {a = r.ProductId, b = r.WarehouseSectionId } equals new { a = rs.ProductId, b = rs.WarehouseSectionId } into joinedL
from rs in joinedL.DefaultIfEmpty()
select new Foo{
qty = rs != null ? r.qty + rs.qty: r.qty};
.NetFiddle实现问题
https://dotnetfiddle.net/Brh74F
现在我可以用 if 语句避免这个问题,但我真的希望能够在纯 linq 中实现正确的左连接。
在
中移除.DefaultIfEmpty()
join rs in reserved.DefaultIfEmpty()
删除.DefaultIfEmpty()
的原因为:
public static System.Collections.Generic.IEnumerable<TSource> DefaultIfEmpty<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, TSource defaultValue);
Returns
IEnumerable<TSource>
An IEnumerable that contains defaultValue if source is empty; otherwise, source.
由于您没有将 defaultValue
传递给 .DefaultIfEmpty()
,因此当 reserved
为空列表时它将 return null
。
和select r
因为你想return来自LEFT的数据table.
var leftOuterJoin = from r in received
join rs in reserved
on new { a = r.ProductId, b = r.WarehouseSectionId } equals new { a = rs.ProductId, b = rs.WarehouseSectionId } into joinedL
from rs in joinedL.DefaultIfEmpty()
select r;
已更新:
如果您正在访问 RIGHT table (rs
),您需要为 rs
null checking
首先 和下一个空大小写处理。
我正在尝试对 2 个列表执行左联接,我 运行 遇到了查询问题,如果右列表为空,则左联接失败。如何更改查询,以便即使列表为空,左连接仍然有效
示例查询:
var received = new List<Foo>{new Foo{ProductId=1,WarehouseSectionId=2, qty= 7}};
var reserved = new List<Foo>{};
var leftOuterJoin = from r in received
join rs in reserved.DefaultIfEmpty()
on new {a = r.ProductId, b = r.WarehouseSectionId } equals new { a = rs.ProductId, b = rs.WarehouseSectionId } into joinedL
from rs in joinedL.DefaultIfEmpty()
select new Foo{
qty = rs != null ? r.qty + rs.qty: r.qty};
.NetFiddle实现问题 https://dotnetfiddle.net/Brh74F
现在我可以用 if 语句避免这个问题,但我真的希望能够在纯 linq 中实现正确的左连接。
在
中移除.DefaultIfEmpty()
join rs in reserved.DefaultIfEmpty()
删除.DefaultIfEmpty()
的原因为:
public static System.Collections.Generic.IEnumerable<TSource> DefaultIfEmpty<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, TSource defaultValue);
Returns
IEnumerable<TSource>
An IEnumerable that contains defaultValue if source is empty; otherwise, source.
由于您没有将 defaultValue
传递给 .DefaultIfEmpty()
,因此当 reserved
为空列表时它将 return null
。
和select r
因为你想return来自LEFT的数据table.
var leftOuterJoin = from r in received
join rs in reserved
on new { a = r.ProductId, b = r.WarehouseSectionId } equals new { a = rs.ProductId, b = rs.WarehouseSectionId } into joinedL
from rs in joinedL.DefaultIfEmpty()
select r;
已更新:
如果您正在访问 RIGHT table (rs
),您需要为 rs
null checking
首先 和下一个空大小写处理。