Ecnalyr
Ecnalyr

Reputation: 5802

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

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.

Upvotes: 4

Views: 1982

Answers (1)

spender
spender

Reputation: 120410

The null-coalescing operator is your friend.

(order.Promo.PercentOff ?? 0)

Upvotes: 13

Related Questions