Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq query, how to check for a null value and use the value 0 in place of a null?

Tags:

c#

linq

I have the following query:

var ordersPlacedBeforeOneHourList = ordersPlacedBeforeOneHourAgo.Select(order => order.Promo.PercentOff * (double) order.TotalCost).ToList();

Some of my order.Promo.PercentOff are null. How can I change the above line so that if order.Promo is null, it behaves as if the values is 0?

The idea is that if there is not a specific promotion applied, I will calculate the cost of the Promotion as 0 * order.TotalCost (which will always be 0), and move on to the next values to calculate where orders.Promo may not be null, and on down the line.

like image 869
Ecnalyr Avatar asked Dec 12 '22 22:12

Ecnalyr


1 Answers

The null-coalescing operator is your friend.

(order.Promo.PercentOff ?? 0)
like image 115
spender Avatar answered Jan 04 '23 23:01

spender