具有可空DateTime的Linq表达式

编程入门 行业动态 更新时间:2024-10-24 06:37:33
本文介绍了具有可空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表达式

本文发布于:2023-11-29 23:19:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647939.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表达式   DateTime   Linq

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!