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
.
FirstOrDefault
on a li开发者_StackOverflow中文版st of integers return a null
value when the list is empty?int? nullableId = GetNonNullableInts().Cast<int?>().FirstOrDefault();
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
精彩评论