具有可空DateTime的Linq表达式 [英] Linq expression with nullable DateTime

查看:40
本文介绍了具有可空DateTime的Linq表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想查询一个可为空的DateTime的实体,例如,选择2005年制造的所有Cars:

I would like to query an entity with a nullable DateTime, for example, select all Cars built in 2005:

public class Car() {
    public int Id {get; set;}
    public DateTime? DateBuilt {get; set;}
    ...
}

我的Linq表达式通常看起来像这样:

My Linq-expression would normally look something like this:

int carsIn2005 = context.Cars.Count(x => x.DateBuilt.Year == "2005");

但是我不能使用.Year,因为Date是可为空的.我已经在Google上搜索了一下,找到了一些关于合并运算符的信息,但是无法从中获得一些有用的信息.如果Linq了解以下内容,那就很酷了:

But I cannot use .Year because the Date is nullable. I've googled a bit, found something about the coalescing-operator, but could not make something usefull from that. Cool would be if Linq understood the following:

int carsIn2005 = context.Cars.Count(x => x.DateBuilt.HasValue && x.DateBuilt.Year == "2005");

如果DateBuilt!= null,那么我应该可以将其视为DateTime.

If DateBuilt != null then I should be able to treat it as a DateTime.

推荐答案

尝试一下

int carsIn2005 = context.Cars.Count(x => x.DateBuilt != null && x.DateBuilt.Value.Year == 2005);

这篇关于具有可空DateTime的Linq表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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