【问题标题】:Need help in resolving error in predicates for And operator in LINQ需要帮助解决 LINQ 中 And 运算符的谓词错误
【发布时间】:2009-01-16 11:59:50
【问题描述】:

我遇到了谓词 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 运算符进行谓词。

提前致谢。
Anil

【问题讨论】:

    标签: .net linq expression predicate


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2020-10-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-09
        • 1970-01-01
        • 1970-01-01
        • 2021-09-10
        相关资源
        最近更新 更多