Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return null instead default value in LINQ

Tags:

c#

linq

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.

like image 576
kat1330 Avatar asked Aug 28 '14 00:08

kat1330


2 Answers

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.

like image 62
Yuliam Chandra Avatar answered Sep 18 '22 15:09

Yuliam Chandra


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.

like image 45
canon Avatar answered Sep 16 '22 15:09

canon