I have the following LINQ query that fires an exception when the FirstOrDefault()
returns null. Ideally I would like to avoid the null check. Is there a way to do this? I wish to return 0
if there are no CPOffsets
that satisfy the FirstOrDefault()
call.
double offset = OrderedOffsets.FirstOrDefault(o => o.OffsetDateTime > cpTime).CPOffset;
The only way I can see to achieve this is the following:
CPOffset cpOffset = OrderedOffsets.FirstOrDefault(o => o.OffsetDateTime > cpTime);
double offset = cpOffset != null ? cpOffset.CPOffset : 0;
Is there another more succinct way? Using Select()
after the FirstOrDefault()
doesn't compile but I thought might be appropriate here?
I think this should work, I'm not near by VS to check it out...
OrderedOffsets.Where(o => o.OffsetDateTime > cpTime).Select(x => x.CPOffset).FirstOrDefault();