开发者

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 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜