问题描述
我有以下代码可帮助我通过反射构建lambda表达式.但是,当我尝试与Date
进行比较时,它将我的值转换为完整的DateTime
标记.如何获取它来构建谓词,以便仅比较短日期?
I have the following code that helps me build a lambda expression via reflection. However when I try to compare versus a Date
it converts my value to a full DateTime
stamp. How can I get it to build my predicate so it will only compare the short date?
System.Reflection.PropertyInfo propInfo = typeof(T).GetProperty(property);
Type propertyType = propInfo.PropertyType;
if (Utilities.IsNullableType(propertyType))
{
propertyType = Nullable.GetUnderlyingType(propertyType);
}
ParameterExpression propAlias = Expression.Parameter(typeof(T), alias);
MemberExpression left = Expression.Property(propAlias, property);
ConstantExpression right = Expression.Constant(Convert.ChangeType(value, propertyType));
BinaryExpression comparer = BuildComparisonExpression(left, right, comparison);
return Expression.Lambda<Func<T, bool>>(comparer, propAlias);
我知道是Convert.ChangeType
会将字符串转换为DateTime
,但是当我想要item => item.DateToCheck == 1/1/2012
时,我得到的是item => item.DateToCheck == 1/1/2012 12:00:00AM
.
I know it's the Convert.ChangeType
that is converting the string to a DateTime
, but what I get back is item => item.DateToCheck == 1/1/2012 12:00:00AM
, when I want item => item.DateToCheck == 1/1/2012
.
推荐答案
您要传递Convert.ChangeType(...)
第三个参数,为此目的已经存在的IFormatProvider
:DateTimeFormatInfo
.
You want to pass Convert.ChangeType(...)
a third argument, the already existing IFormatProvider
for this exact purpose: DateTimeFormatInfo
.
这篇关于使用短日期构建动态Lambda谓词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!