1

我遇到了谓词 And 运算符的问题。代码是:

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"]));
   }
}

错误是行:[ else {pred = pred.And(c => ] 方法 'And' 没有重载需要 '1' 参数

谁能告诉我如何使用 .And 运算符进行谓词。

提前致谢。
阿尼尔

4

2 回答 2

4

And是二元 And 运算符;你Expression.AndAlso的意思是

pred = Expression.AndAlso(pred, {new bit})

但是,我怀疑您正在以艰难的方式做到这一点。使用以下内容更容易:

IQueryable<Foo> source = ...
if(condition1) {
    source = source.Where(predicate1);
}
if(condition2) {
    source = source.Where(predicate2);
}

例如:

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));
}
于 2009-01-16T12:08:01.810 回答
0

一个漂亮的小库是来自 C# 3.0 的 Predicate Builder in a Nutshell Guy - http://www.albahari.com/nutshell/predicatebuilder.aspx

于 2009-01-16T12:56:47.953 回答