Reputation: 60741
I am going through a codereview and seeing something suspicious.
In the snippet below can result ever be NULL ?
var result = (from number in _cmContext.SrvLocationWarmLine
where String.Compare(number.CurrentWarmLine, startingRange, StringComparison.Ordinal) >= 0
&& String.Compare(number.CurrentWarmLine, endingRange, StringComparison.Ordinal) <= 0
orderby number.CurrentWarmLine descending
select new { Number = number.CurrentWarmLine }).FirstOrDefault();
More generally: when applying FirstOrDefault against a select, can the result ever be null?
Upvotes: 1
Views: 867
Reputation: 43886
Yes. The result
is null
if the sequence is empty.
This happens if no number
in _cmContext.SrvLocationWarmLine
matches the condition in the where
clause.
In general FirstOrDefault()
(without a predicate argument) returns null
for an empty sequence (no matter if that sequence was returned by a select
or from something different).
The FirstOrDefault<T>(this IEnumerable<T>, Predicate<T>)
returns null
if there is no element in the sequence matching the predicate.
Note that the select
in the query syntax is translated into a Select(...)
method call.
Edit: of course the above applies only if the type of the elements of the final sequence is a reference type. For value types the result would be default(type)
, e.g. 0
for an int
.
Upvotes: 3