Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

linq

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?

like image 854
Boris Callens Avatar asked Dec 01 '09 10:12

Boris Callens


People also ask

Can FirstOrDefault return null?

The major difference between First and FirstOrDefault is that First() will throw an exception if there is no result data for the supplied criteria whereas FirstOrDefault() returns a default value (null) if there is no result data.

What does FirstOrDefault return if empty?

If a collection is empty, FirstOrDefault returns the default value for the type. The method internally checks if an element exists. Simple example. Here we show what happens when FirstOrDefault is used on a non-empty collection, and then an empty collection.

What is the default value returned by FirstOrDefault?

The default value for reference and nullable types is null . The FirstOrDefault method does not provide a way to specify a default value. If you want to specify a default value other than default(TSource) , use the DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource) method as described in the Example section.

What is FirstOrDefault method in C#?

Use the FirstorDefault() method to return the first element of a sequence or a default value if element isn't there. List<double> val = new List<double> { }; Now, we cannot display the first element, since it is an empty collection.


2 Answers

int? nullableId = GetNonNullableInts().Cast<int?>().FirstOrDefault(); 
like image 153
Matt Howells Avatar answered Sep 21 '22 20:09

Matt Howells


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

like image 34
Rubens Farias Avatar answered Sep 22 '22 20:09

Rubens Farias