Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ ANY() with First() And FirstOrDefault()

I've written code like this

TotalCashIn = totals != null && totals.Any() ? totals.First().TotalCashIn : null;

And i have been blamed for this code and have told to write like this

TotalCashIn = totals != null ? totals.FirstOrDefault().TotalCashIn : null;

But I am wondering would not I get an exception if totals count would be 0? Do I need also check this with .Any() or .Count()?

like image 676
So_oP Avatar asked Feb 20 '18 07:02

So_oP


1 Answers

You can use the null-conditional operator to make all of this a lot simpler, assuming that the element type of totals is a reference type:

TotalCashIn = totals?.FirstOrDefault()?.TotalCashIn;

With this:

  • If totals is null, the overall result is null due to the first null-conditonal operator
  • If totals is empty, FirstOrDefault() will return null, so the overall result is null due to the second null-conditional operator
  • Otherwise, the result is the TotalCashIn property of the first element
like image 66
Jon Skeet Avatar answered Nov 10 '22 16:11

Jon Skeet