如何对具有 where 子句的 linq 字段求和,该子句也提取 returns 为空的数据?

How to sum a field on linq that has a where clause which pulls data that returns nulls too?

我有一个 LINQ 查询,它按公司的仓库描述分组。现在,我必须计算当月物品的重量。但是我有另一个字段,它总结了废料的总重量,这是由包含单词 "SCRP" 的字段找到的。当我这样做时,我得到臭名昭著的对象引用错误未设置为对象错误的实例。我认为这是因为有空值或其他东西。该字段包含其他值或空值。

这是我的查询。它运行完美,直到我尝试添加 UserSequence 位:

P.s 报废百分比也不起作用,但我认为这是因为同样的问题。

var fistDayofPreviousMonth = DateTime.Today.AddMonths(-4);
var testScrapQuery = from s in mapicsSession.Query<InventoryHistory>()
                     where s.PostedTimestamp > fistDayofPreviousMonth
                     orderby s.Warehouse.Description
                     group s by s.Warehouse.Description
                     into test
                     let tw = mapicsSession.Query<InventoryHistory>()
                         .Where(x => x.Warehouse.Description == test.Key)
                         .Sum(x => x.Item.Weight)
                     let sw = mapicsSession.Query<InventoryHistory>()
                         .Where(x => x.Warehouse.Description == test.Key 
                                     && x.UserSequence == "SCRP")
                         .Sum(x => x.Item.Weight)
                     select new
                     {
                         Warehouse = test.Key,
                         TotalWeight = tw,
                         ScrapWeight = sw
                         //ScrapPercentage = (sw / tw) * 100
                     };

您可以通过合并值来解决第一个问题(现在如果 xx.Item 为 null,它会将 0 作为一个值):

.Sum(x => x?.Item?.Weight ?? 0)

或额外 Where:

.Where(x => x != null && x.Item != null)
.Sum(x => x.Item.Weight)

而且我想这可以用于您的百分比计算(防止除以 0):

ScrapPercentage = tw == 0 ? 100 : (sw / tw) * 100