I just read a SO post that explained that FirstOrDefault()
's return type will vary based on the value of the element being selected.
Example:
ICollection<String> list = new List<String>();
list.Add("bye");
int a = (from x in list where (x == "hi") select x.Length).FirstOrDefault();
In this example, a
will be equal to 0 since the int
default value is 0.
However, I can append .Cast<int?>()
as per the already linked post in order to get null
when the query returns 0 results.
int? a = (from x in list where ... x.Length).Cast<int?>().FirstOrDefault();
Why don't I get a compile-time error (or at least a warning) when, for my first example, I use a Nullable int (int?
) rather than a regular int
?
If I understand correctly, using a int?
when performing my first query will never result in a value of 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() will return the default value (null) if there is no result data.
FirstOrDefault<TSource>(IEnumerable<TSource>, TSource) Returns the first element of a sequence, or a specified default value if the sequence contains no elements. FirstOrDefault<TSource>(IEnumerable<TSource>) Returns the first element of a sequence, or a default value if the sequence contains no elements.
SingleOrDefault() – Same as Single(), but it can handle the null value. First() - There is at least one result, an exception is thrown if no result is returned. FirstOrDefault() - Same as First(), but not thrown any exception or return null when there is no result.
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.
Why don't I get a compile-time error (or at least a warning) when, for my first example, I use a Nullable
int
rather than a regularint
then? If I understand correctly, using a int? when performing my first query will never result in a value ofnull
.
Your understanding is correct. However, the compiler does not interfere with your desire to declare variable a
as nullable, because it is a "widening" conversion: even though the assignment from the LINQ query would never return a null
, you may have other use for the same variable down below:
int? a = (from x in list where (x == "hi") select x.Length).FirstOrDefault();
// Do something with `a`, which will not be null
...
a = null;
if (someCondition) {
a = someNotNullValue();
}
// Here, a may or may not be null
...
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