在LINQ中返回null而不是默认值 [英] Return null instead default value in LINQ

查看:131
本文介绍了在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.

这篇关于在LINQ中返回null而不是默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆