You've got the null-coalescing operator in the wrong place - currently you're calling Where
on payment.NewInvoiceModels
unconditionally and then checking whether the result will be null... it never will be (Where
simply doesn't return null). You potentially want:
foreach (var pmt in (payment.NewInvoiceViewModels ??
Enumerable.Empty<NewInvoiceViewModel>())
.Where(x => x.PaymentReceived != 0))
Personally I'd extract this out though:
var allModels = payment.NewInvoiceViewModels ??
Enumerable.Empty<NewInvoiceViewModel>();
foreach (var pmt in allModels.Where(x => x.PaymentReceived != 0))
Or perhaps introduce an extension method:
public static IEnumerable<T> NullToEmpty(this IEnumerable<T> source)
{
return source ?? Enumerable.Empty<T>();
}
Then:
foreach (var pmt in payment.NewInvoiceViewModels
.NullToEmpty()
.Where(x => x.PaymentReceived != 0))