如何在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
相关产品推荐
相关产品推荐

