在LINQ中返回null而不是默认值

问题描述:

我有LINQ查询,该查询必须检索一些DateTime值.我没有匹配的某些主题,我必须为该DateTime值返回NULL,而不是DateTime的默认值.

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.

如何避免这种情况并返回NULL而不是默认值?

How can I avoid that and return NULL instead defaul value?

我的LINQ:

CreatedDate = ctaMatch.Select(d => d.CreatedDate).DefaultIfEmpty().FirstOrDefault()

在DefaultIfEmpty中,我只能放置DateTime.

In DefaultIfEmpty I can put only DateTime.

将其投射到DateTime?,这将导致DefaultIfEmpty创建一个默认集合,如果该集合为空,则该集合将包含空值.

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:可以省略DefaultIfEmpty,因为它后面是FirstOrDefault.

PS: The DefaultIfEmpty can be omitted, because it's followed by FirstOrDefault.