Boris Callens
Boris Callens

Reputation: 93287

Return null for FirstOrDefault() on empty IEnumerable<int>?

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

Answers (2)

Rubens Farias
Rubens Farias

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

Matt Howells
Matt Howells

Reputation: 41266

int? nullableId = GetNonNullableInts().Cast<int?>().FirstOrDefault();

Upvotes: 61

Related Questions