0

I have a problem with my linq query. I get a null reference exception. What's wrong with my code? I do null checks but still get an exception.

What am I doing wrong?

Math.Round(invoiceData?.Lines?.Sum(x => x.Amount) ?? 0, 2); 

Thanks in advance.

mrjasmin
  • 1,230
  • 6
  • 21
  • 37

1 Answers1

0

Have you tried to do like:

Math.Round(invoiceData?.Lines?.Sum(x => x.Amount ?? 0), 2); 
federico scamuzzi
  • 3,708
  • 1
  • 17
  • 24
  • Hi! That won't work. Amount is a decimal and you can't use the null coalescing operator there. – mrjasmin Dec 29 '16 at 08:48
  • 1
    ah ok ... so maybe try something like: Math.Round(invoiceData?.Lines?.Where(item=>item!=null && item.Amount != null).Sum(x => x.Amount) ?? 0, 2); – federico scamuzzi Dec 29 '16 at 08:51