Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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?
–
–
–
–
–
–
DefaultIfEmpty
can be used to ensure that the collection always has at least one element.
double offset = OrderedOffsets.Where(o => o.OffsetDateTime > cpTime)
.Select(o => o.CPOffset)
.DefaultIfEmpty()
.First();
–
–
I think a good pattern could be :
double offset = (OrderedOffsets.FirstOrDefault(o => o.OffsetDateTime > cpTime) ?? someDefaultObject).CPOffset;
with someDefaultObject
an object holding default values... With this pattern, you can change easily you default values through your code !
If OrderedOffsets can be a struct you could also just put your default value there ! :)
–
–
–
–
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.