Search code examples
c#lambdaexpressionpredicatepredicatebuilder

Manuel Expression Builder contains doesnt work because of null value in list


var people = new[] {
                new myUserListObject { userobj = new User { Email = "[email protected]"},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"))}

i doing dynamic predicate builder. but Contains doesnt work because of nullable values. and lastline throw 'System.NullReferenceException: 'object reference not set to an instance of an object.'

Anybody help me? Where is my fault? Also I'am sorry for my english so bad.


Solution

  • Expression.And is the & operator, which does not short-circuit : it will evaluate both sides. You want Expression.AndAlso - which maps to &&