You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LINQ多列左外连接(Left Outer Join)查询返回0行结果问题求助

问题根因
  • 左连接语法错误:你在join rs in reserved.DefaultIfEmpty() 中错误添加了DefaultIfEmpty(),该方法应当仅作用于join后的分组结果,join源列表时不需要添加,否则会导致匹配逻辑异常。
  • 空引用异常被吞导致结果计数为0:左连接未匹配到对应reserved条目时,rs变量会为null,你直接访问rs.QTY会触发NullReferenceException,若上层代码捕获了异常未抛出,就会出现返回结果为空的情况,这也是你注释掉rs相关赋值后查询正常的核心原因。
修正后代码
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 new
                    {
                        SKU = r.SKU,
                        ProductName = r.ProductName,
                        QTY = r.QTY,
                        // 先判断rs是否为null,避免空引用
                        PhysicalStock = rs != null && rs.QTY > 0 ? r.QTY + rs.QTY : r.QTY,
                        WarehouseSection = r.WarehouseSection,
                        WarehouseName = r.WarehouseName,
                        ProductId = r.ProductId,
                        WarehouseSectionId = r.WarehouseSectionId
                    };
补充说明

如果你的QTY是不可空的值类型,不需要额外判断rs.QTY != null;如果是可空类型int?,可以调整判断为rs != null && rs.QTY.HasValue && rs.QTY.Value > 0即可。

内容的提问来源于stack exchange,提问作者nightwolf555

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 01:06:03