Reputation: 93287
Say I have the following snippet:
int? nullableId = GetNonNullableInts().FirstOrDefault();
Because GetNonNullableInts()
returns integers, the FirstOrDefault
will default to 0
.
Is there a way to make the FirstOrDefault
on a list of integers return a null
value when the list is empty?
Upvotes: 34
Views: 23338
Reputation: 57936
FirstOrDefault
depends on T
from IEnumerable<T>
to know what type to return, that's why you're receiving int
instead int?
.
So you'll need to cast your items to int?
before return any value, just like Matt said
Upvotes: 1
Reputation: 41266
int? nullableId = GetNonNullableInts().Cast<int?>().FirstOrDefault();
Upvotes: 61