If I have a query that returns a DateTime
, what's the value of FirstOrDefault()
? Is there a generic way to get the default value of a C# scalar? Example:
var list = (from item in db.Items
where item.ID==1234
select item.StartDate).FirstOrDefault();
Edit: Assume that the column StartDate
can't be null.
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.
FirstOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>, TSource) Returns the first element of the sequence that satisfies a condition, or a specified default value if no such element is found.
FirstOrDefault works same as First() does, FirstOrDefault returns the first element from a sequence, but here there is an advantage over First(), so if there is no record in the collection which matches input criteria then FirstOrDefault() can handle null values and it does not throw an exception. Conclusion.
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.
The generic way to get a default value for a given generic type is:
default(T)
where T
is the generic type parameter in question. For reference types, this will yield null
. For value types, this will yield a zero'd instance of the value. For DateTime
s, this will be equivalent to DateTime.MinValue
.
DateTime.MinValue
default(DateTime)
is 1/1/0001 12:00:00 AM.
In your code, the major portion of your query is an IEnumerable of start dates from your database. Your call to FirstOrDefault() is either returning the first element of the enumerable or the default value of its type if there are no elements in the enumerable.
If the type of StartDate is indeed a date and there are no elements in the enumerable, then the result will be the datetime value I provided above.
Im guessing its default(DateTime)
which im guessing (again) is DateTime.MinValue
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