user4648142 user4648142 - 1 month ago 5
ASP.NET (C#) Question

Select Linq statement needs to return 0 if either item is null

I am doing a query for 2 different integers and at least one them needs to be over 0. That works fine by when I'm doing the select statement I compute the stock based on those with the

.Sum()
method which gives me a null exception if either
int
is
null
which that needs to return 0.

I know about
DefaultIfEmpty(0)
but all the other questions did it differently then how I'm doing it and I'm computing 2 different variables in the select statement and I'm not experienced enough to be able to rework this query.

public IEnumerable<Item> GetInStockTooling()
{
try
{
using (var context = new SpectrumContext())
{
var inStock = context.Item
.Include(i => i.ItemType)
.Include(i => i.ItemLots)
.Include(i => i.LocationStocks)
.Where(w => w.ItemLots.Any(a => a.Quantity > 0 && a.JobItemID == null) || w.LocationStocks.Any(a => a.AmountOfStock > 0) && w.ItemTypeID == (int)ItemTypes.Tooling && w.IsActive)
.Select(b => new
{
b,
ItemLots = b.ItemLots.Where(w => w.JobItemID == null && w.Quantity > 0),
ItemType = b.ItemType,
LocationStocks = b.LocationStocks.Where(w => w.AmountOfStock > 0)
})
.AsEnumerable()
.Select(x => x.b)
.ToList()
.Select(x => { x.Stock = x.ItemLots.Sum(s => s.Quantity) + x.LocationStocks.Sum(s => s.AmountOfStock); return x; });

return inStock;
}
}
catch (Exception)
{
throw;
}
}


I've tried to do
?? 0
and
?? 0m
on on quantity/AmountOfStock but I get an
Operand cannot be applied to type 'decimal' and 'decimal'
error.

I've also tried using
DefaultIfEmpty
but I have no idea where to use it considering they are doing all the computing inside the
Select
and I don't know how I would pull it out of the
Select
for use of
DefaultIfEmpty
.

Answer

Try to check for null then return 0 else return the number. Using ternary operator here you go:

 x.ItemLots.Sum(s => { return s.Quantity == null ? 0 : s.Quantity; }) + x.LocationStocks.Sum(s => { s.AmountOfStock == null ? 0 : s.AmountOfStock; });