I have LINQ query which has to retreive some DateTime value. Somethimes I don't have match for and I have to return NULL for that DateTime value instead default value for DateTime.
How can I avoid that and return NULL instead defaul value?
My LINQ:
CreatedDate = ctaMatch.Select(d => d.CreatedDate).DefaultIfEmpty().FirstOrDefault()
In DefaultIfEmpty I can put only DateTime.
Cast it to DateTime?
that will cause DefaultIfEmpty
creates a default collection that contains null value if the collection is empty.
CreatedDate = ctaMatch
.Select(d => (DateTime?)d.CreatedDate)
.DefaultIfEmpty()
.FirstOrDefault()
PS: The DefaultIfEmpty
can be omitted, because it's followed by FirstOrDefault
.
You could use the null-conditional operator, ?.
on the object hosting your date property:
DateTime? date = ctaMatch.FirstOrDefault()?.CreatedDate;
If FirstOrDefault()
returns null
for your collection, the null-conditional operator will return null
for the CreatedDate
property.
Alternatively, you could select your dates and cast them explicitly to Nullable<DateTime>
.
DateTime? date = ctaMatch.Select(d => (DateTime?)d.CreatedDate).FirstOrDefault();
... thereby giving it a default value of 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