Building dynamic lambda predicate with short date

2019-08-12 03:47发布

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条回答
We Are One
2楼-- · 2019-08-12 04:39

You want to pass Convert.ChangeType(...) a third argument, the already existing IFormatProvider for this exact purpose: DateTimeFormatInfo.

查看更多
登录 后发表回答