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
.
Alternative syntax... get the First
element if Any
exist; otherwise use null
:
DateTime? CreatedDate = ctaMatch.Any() ? ctaMatch.First().CreatedDate : (DateTime?)null;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.