Reputation: 1405
I got into problem of predicate And operator. Code is :
SQLDBDataContext sqlDS = new SQLDBDataContext();
Expression<Func<User,bool>> pred = null; //delcare the predicate to start with.
if (Request["Name"] != null && ! Request["Name"].Equals(string.Empty))
{
pred = c => ( c.ContactFirst.Contains(Request["Name"]) || c.ContactLast.Contains(Request["Name"]));
}
if (Request["Company"] != null && !Request["Company"].Equals(string.Empty))
{
if (pred == null) {
pred = (c => c.Company.Contains(Request["Company"]));
}
else {
pred = pred.And(c => c.Company.Contains(Request["Company"]));
}
}
error is line : [ else {pred = pred.And(c => ] No overload for method 'And' takes '1' arguments
Can anybody tell me how to use .And operator to predicate.
Thanks in advance.
Anil
Upvotes: 2
Views: 737
Reputation: 25099
A nifty little library to have is the Predicate Builder from the C# 3.0 in a Nutshell guys - http://www.albahari.com/nutshell/predicatebuilder.aspx
Upvotes: 0
Reputation: 1062855
And
is the binary And operator; you mean Expression.AndAlso
, i.e.
pred = Expression.AndAlso(pred, {new bit})
However, I suspect you are doing this the hard way. It is easier to use things like:
IQueryable<Foo> source = ...
if(condition1) {
source = source.Where(predicate1);
}
if(condition2) {
source = source.Where(predicate2);
}
For example:
IQueryable<User> source = ...
string name = Request["Name"];
if(!string.IsNullOrEmpty(name)) {
source = source.Where(user => user.ContactFirst.Contains(name)
|| user.ContactLast.Contains(name));
}
string company = Request["Company"];
if(!string.IsNullOrEmpty(company)) {
source = source.Where(user => user.Company.Contains(company));
}
Upvotes: 4