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()?

Jon Skeet
people
quotationmark

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

people

See more on this question at Stackoverflow