由于列表中的空值,手动表达式生成器包含不起作用
Manuel Expression Builder contains doesnt work because of null value in list
var people = new[] {
new myUserListObject { userobj = new User { Email = "test@gmail.com"},Session=3 },
new myUserListObject { userobj= new User { Email = null }, Session=4}
};
var peopList = people.ToList();
var parameterExp = Expression.Parameter(typeof(myUserListObject), "type");
Expression propertyExp = Expression.Property(parameterExp, "userobj");
propertyExp = Expression.Property(propertyExp, "Email");
MethodInfo methodd = typeof(string).GetMethod("Contains", new[] { typeof(string) });
var someValued = Expression.Constant("gmail", typeof(string));
var containsMethodExpd = Expression.Call(propertyExp, methodd, someValued);
var resxx = Expression.NotEqual(propertyExp, Expression.Constant(null, propertyExp.Type));
var togerther = Expression.And(resxx, containsMethodExpd);
var toglamb = Expression.Lambda<Func<myUserListObject, bool>>(togerther, parameterExp);
var tt = peopList.AsQueryable().Where(toglamb).ToList(); //toglamb is {type => ((type.userobj.Email != null) And type.userobj.Email.Contains("gmail"))}
我在做动态谓词生成器。但 Contains 由于可为空值而不起作用。最后一行 throw 'System.NullReferenceException: 'object reference not set to an instance of an object.'
有人帮帮我吗?我的错在哪里?
另外我很抱歉我的英语太差了。
Expression.And
是 &
运算符,它 不会短路 :它将评估双方。您想要 Expression.AndAlso
- 映射到 &&
var people = new[] {
new myUserListObject { userobj = new User { Email = "test@gmail.com"},Session=3 },
new myUserListObject { userobj= new User { Email = null }, Session=4}
};
var peopList = people.ToList();
var parameterExp = Expression.Parameter(typeof(myUserListObject), "type");
Expression propertyExp = Expression.Property(parameterExp, "userobj");
propertyExp = Expression.Property(propertyExp, "Email");
MethodInfo methodd = typeof(string).GetMethod("Contains", new[] { typeof(string) });
var someValued = Expression.Constant("gmail", typeof(string));
var containsMethodExpd = Expression.Call(propertyExp, methodd, someValued);
var resxx = Expression.NotEqual(propertyExp, Expression.Constant(null, propertyExp.Type));
var togerther = Expression.And(resxx, containsMethodExpd);
var toglamb = Expression.Lambda<Func<myUserListObject, bool>>(togerther, parameterExp);
var tt = peopList.AsQueryable().Where(toglamb).ToList(); //toglamb is {type => ((type.userobj.Email != null) And type.userobj.Email.Contains("gmail"))}
我在做动态谓词生成器。但 Contains 由于可为空值而不起作用。最后一行 throw 'System.NullReferenceException: 'object reference not set to an instance of an object.'
有人帮帮我吗?我的错在哪里? 另外我很抱歉我的英语太差了。
Expression.And
是 &
运算符,它 不会短路 :它将评估双方。您想要 Expression.AndAlso
- 映射到 &&