且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-12-05 11:30:26

将其投射到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.