use*_*247 3 c# linq lambda expression linq-extensions
我有一个可以为空的datetime字段,我必须将string日期字段转换为可以为空的日期时间类型(使用Expression)....我使用下面的方法做了这个.
Expression.Constant(Convert.ChangeType(value, Nullable.GetUnderlyingType(memberAccess.Type)));.
Run Code Online (Sandbox Code Playgroud)
memberAccess(如上所述)是成员表达式.(来自LinqExtensions.cs)现在我在代码中使用Expression.Equal方法.
Expression.Equal(memberAccess, filter);
Run Code Online (Sandbox Code Playgroud)
这里失败了,因为memberaccess类型可以为空但filter.type不可为空...
即使我尝试使用成员访问类型转换为可空
ConstantExpression test = Expression.Constant(Nullable.GetUnderlyingType(memberAccess.Type)),
Run Code Online (Sandbox Code Playgroud)
Type是Runtime而不是DateTime.
如何使用Expression.Equal比较可空和不可空的字段?有没有办法将字符串类型转换为可空的日期时间字段?其中任何一个都可以解决我的问题.
好的..我这样做了.
首先转换类型(字符串到日期时间)
filter = Expression.Constant(
Convert.ChangeType(value, memberAccess.Type.GetGenericArguments()[0]));
Run Code Online (Sandbox Code Playgroud)
然后将此表达式转换为所需的类型
Expression typeFilter = Expression.Convert(filter, memberAccess.Type);
Run Code Online (Sandbox Code Playgroud)
然后使用 Expression.Equal(memberAccess, typeFilter)...
(memberAccess is MemberExpression它从模型中获取属性类型)