简体   繁体   English

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

[英]Return null instead default value in LINQ

I have LINQ query which has to retreive some DateTime value. 我有LINQ查询,它必须检索一些DateTime值。 Somethimes I don't have match for and I have to return NULL for that DateTime value instead default value for DateTime. Somethimes我没有匹配,我必须为该DateTime值返回NULL而不是DateTime的默认值。

How can I avoid that and return NULL instead defaul value? 我怎样才能避免这种情况并返回NULL而不是默认值?

My LINQ: 我的LINQ:

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

In DefaultIfEmpty I can put only DateTime. 在DefaultIfEmpty中,我只能放置DateTime。

Cast it to DateTime? 把它DateTime? that will cause DefaultIfEmpty creates a default collection that contains null value if the collection is empty. 这将导致DefaultIfEmpty创建一个默认集合,如果集合为空,则该集合包含空值。

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

PS: The DefaultIfEmpty can be omitted, because it's followed by FirstOrDefault . PS:可以省略DefaultIfEmpty ,因为它后跟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. 如果FirstOrDefault()为集合返回null ,则null条件运算符将为CreatedDate属性返回null

Alternatively, you could select your dates and cast them explicitly to Nullable<DateTime> . 或者,您可以选择日期并将它们显式转换为Nullable<DateTime>

DateTime? date = ctaMatch.Select(d => (DateTime?)d.CreatedDate).FirstOrDefault();

... thereby giving it a default value of null . ...从而给它一个默认值null

Alternative syntax... get the First element if Any exist; 替代语法...拿到First元素,如果Any存在; otherwise use null : 否则使用null

DateTime? CreatedDate = ctaMatch.Any() ? ctaMatch.First().CreatedDate : (DateTime?)null;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM