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()?
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:
totals is null, the overall result is null due to the first null-conditonal operatortotals is empty, FirstOrDefault() will return null, so the overall result is null due to the second null-conditional operatorTotalCashIn property of the first elementIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With