求一恒真恒假的 lambda Express 表达式
当Value为NULL时,如果返回一个真的表达式
1 方法如下 :
public static Expression<Func<T, bool>> ExpressionEqual<T, P>(this T entity, string property, P value) where T:class
{
if (value == null)
{
//
}
ParameterExpression param = Expression.Parameter(typeof(T), "entity");
Expression left = Expression.Property(param, typeof(T).GetProperty(property));
left = Expression.Convert(left, value.GetType());
Expression right = Expression.Constant(value);
Expression filter = Expression.Equal(left, right);
Expression<Func<T, bool>> predicate = Expression.Lambda<Func<T, bool>>(filter, param);
return predicate;
}
2 外部调用
class aClass
{
public string code {get;set}
}
var a = new aClass()
var queryWhere = a.ExpressionEqual("code",a.code);
var resule = aRespostion.getAll().where(queryWhere).tolist();
------解决方案--------------------
if (value == null)
{
return a=> true;
}