c#安全导航操作符,避免除零异常

时间:2022-01-22 11:46:40

I'm creating an excel report that calculates the weighted average cost across a span of months. This is for 100+ months, and some of these months do not have any quantity. If the month doesn't have a quantity, I set it to 0 to avoid a null exception error.

我正在创建一个excel报告,计算几个月的加权平均成本。这是100多个月,其中一些月没有任何数量。如果月没有一个量,我将它设置为0以避免null异常错误。

When generating the report I get a divide by zero exception for those months without a quantity. Is there a way to check if the value is 0 in a sum calculation using the safe navigation (.?) operator?

在生成报告时,我得到了一个除零例外,在那些没有数量的月份。是否有一种方法可以使用安全导航(.?)操作符检查求和计算中的值是否为0 ?

Here's what I've tried, to no avail:

以下是我试过的,但毫无用处:

Setting the property to 0m if the quantity is null :

如果数量为空,则将属性设置为0m:

     WeightedQty = (x.Item2 / 100m) * x.Item1?.qty ?? 0m

Doing the sum calculation where I get the divide by zero error:

做求和计算,我得到的除法是零误差:

     WeightedCost = accrual_qtys.Sum(y => y.Quantity * key.wac) /  accrual_qtys.Sum(y => y.WeightedQty == 0m ? y.WeightedQty : 1m)

1 个解决方案

#1


1  

please try this

请试试这个

 WeightedCost = accrual_qtys.Sum(y => y.Quantity * key.wac) /  (accrual_qtys.Any(y => y.WeightedQty > 0m) ? accrual_qtys.Sum(y => y.WeightedQty) : 1m))

#1


1  

please try this

请试试这个

 WeightedCost = accrual_qtys.Sum(y => y.Quantity * key.wac) /  (accrual_qtys.Any(y => y.WeightedQty > 0m) ? accrual_qtys.Sum(y => y.WeightedQty) : 1m))