You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在System.Linq.Dynamic.Core中实现Date为空/非空判断?

在System.Linq.Dynamic.Core中实现日期为空/非空判断的正确写法

你的原代码无法生效的核心问题是:用空字符串''和日期类型字段做比较,这会导致类型不匹配——日期类型(无论是可空的DateTime?还是不可空的DateTime)都不能直接与字符串常量进行比较。

针对不同的日期字段类型,正确的写法如下:

场景1:字段为可空日期类型DateTime?

可空日期的“空”对应null,直接判断字段与null的关系即可:

if (filter.Operator.StartsWith("is empty") || filter.Operator.StartsWith("is not empty"))
{
    filterOp = filter.Operator.StartsWith("is not") ? "!= null" : "== null";
    qs = $"{filter.Column.PropertyName} {filterOp}";
}
query = query.Where(qs);

场景2:字段为不可空日期类型DateTime

不可空日期本身不会为null,如果业务上需要把DateTime.MinValue视为“空”,可以直接与该常量比较:

if (filter.Operator.StartsWith("is empty"))
{
    qs = $"{filter.Column.PropertyName} == DateTime.MinValue";
}
else if (filter.Operator.StartsWith("is not empty"))
{
    qs = $"{filter.Column.PropertyName} != DateTime.MinValue";
}
query = query.Where(qs);

内容的提问来源于stack exchange,提问作者mz1378

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 09:04:53