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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With