【发布时间】:2018-11-30 08:00:45
【问题描述】:
我想对空值进行动态检查。 我想创建一个 where 子句,它只比较日期字段的日期部分。
它适用于不可为空的日期字段,但对于可空的日期字段,我们需要检查值,因为在空数据上使用 .Date 会引发错误
让我们说
p => (p.Date.Value == null ? null : p.Date.Value.Date) == SelectedDate.Date
或
p => ( p.Date.Value == null ? p.Date.Value : p.Date.Value.Date) == SelectedDate.Date
或
p => (p.Date.Value == null ? p.Date : p.Date.Value.Date) == SelectedDate.Date
基本上是一个空检查三元运算符,它只选择
的日期部分我已经试过了
ConstantExpression argument = Expression.Constant(MyDateField, typeof(DateTime));
ParameterExpression parameter = Expression.Parameter(typeof(T), "p");
string field = "Date";
BinaryExpression condition = Expression.Equal(Expression.Property(parameter, field), Expression.Constant(null, typeof(DateTime?)));
ConditionalExpression ternary = Expression.Condition(condition, property, Expression.Property(property, "Date"));
Expression equalExp = Expression.Equal(ternary, argument);
lambda = Expression.Lambda<Func<T, bool>>(equalExp, parameter);
这给了我
p => (IIF((p.EventDate == null), p.EventDate.Value, p.EventDate.Value.Date) == 21-Jun-18 12:00:00 AM)
但这不起作用。 我面临的问题是
如果我在 BinaryExpression 中使用 p.Date.Value 那么它不允许,因为 .Value 使它成为 DateTime 并且 null 仅在 DateTime 中可用?
IIF 条件生成而不是?: 三元运算符
感谢任何和所有的帮助。
【问题讨论】:
-
@Amit 这里的类型是DateTime?或者Nullable
-
@SirRufo 是的,那个问题也有。我可能已经看到这里的 OP 正在使用 DateTime? ..让我再读一遍
-
@Amit 第二段:但是对于可为空的日期字段我们需要检查
-
p.Date.Value == null ? null : p.Date.Value.Date这已经错了。p.Date == null ? (DateTime?)null : (DateTime?)p.Date.Value.Date
标签: c# linq where-clause expression-trees dynamic-linq