问题
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);
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
.
回答1:
You want to pass Convert.ChangeType(...)
a third argument, the already existing IFormatProvider
for this exact purpose: DateTimeFormatInfo
.
来源:https://stackoverflow.com/questions/13405785/building-dynamic-lambda-predicate-with-short-date