Building dynamic lambda predicate with short date

瘦欲@ 提交于 2020-01-24 19:50:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!