c#反射表达式树模糊搜索示例
public static expression<func<t, bool>> getsearchexpression<t>(string searchstring)
{
expression<func<t, bool>> filter = null;
if (string.isnullorempty(searchstring)) return null;
var left = expression.parameter(typeof(t), "m");
expression expression = expression.constant(false);
t obj = default(t);
var type = typeof(t);
obj = (t)activator.createinstance(type);
var propertyinfos = type.getproperties();
foreach (var propertyinfo in propertyinfos)
{
if (propertyinfo.name.tolower() == "id" || propertyinfo.propertytype == typeof(datetime)) continue;
expression tostring = expression.call
(
expression.property(left, typeof(t).getproperty(propertyinfo.name).name),
typeof(object).getmethod("tostring", new type[] { })
);
expression right = expression.call
(
tostring,
typeof(string).getmethod("contains", new type[] { typeof(string) }),
expression.constant(searchstring)
);
expression = expression.or(right, expression);
}
filter = expression.lambda<func<t, bool>>(expression, new[] { left });
return filter;
}