2013-02-10 72 views
1

我有以下功能如何结合2 Linq的谓词〜C#

public virtual ICollection<T> initData<T>(System.Data.Entity.DbSet<T> set, System.Linq.Expressions.Expression<Func<T, bool>> filter) where T : CModel<T> 
     { 
      var x = (from dc in set select dc); 
      if (!this.db.valid) 
      { 
       System.Linq.Expressions.Expression<Func<T, bool>> active = a => a.active; 
       filter = (Expression<Func<T, bool>>)Expression.Lambda(Expression.AndAlso(filter, active)); 
       x.Where(filter); 

      } 
      else 
      { 
       x.Where(filter); 
      } 
      return (ICollection<T>)x.ToList(); 
     } 

当过我尝试了2个谓词与AndAlso结合我抛出一个异常:

The binary operator AndAlso is not defined for the types 'System.Func`2[namespace.Models.MyClass,System.Boolean]' and 'System.Func`2[namespace.Models.MyClass,System.Boolean]'. 

我怎么能结合这两个条件?

+0

您可以使用谓词构建器。 http://www.albahari.com/nutshell/predicatebuilder.aspx – Flowerking 2013-02-10 10:57:04

+0

[LINQ to Entities:Combining Predicates](http://blogs.msdn.com/b/meek/archive/2008/05/02/linq-到实体,合并,predicates.aspx) – 2014-06-17 05:38:16

回答

1

我认为你正在为自己而努力。你可以只使用Where扩展方法多次这样的:

public virtual ICollection<T> initData<T>(System.Data.Entity.DbSet<T> set, System.Linq.Expressions.Expression<Func<T, bool>> filter) where T : CModel<T> 
{ 
    var x = (from dc in set select dc); 
    x = set.Where(filter); 

    if (!this.db.valid) 
    { 
     x = x.Where(a => a.active); 
    } 

    return x.ToList(); 
} 

注意,在你的代码中使用x.Where(filter);
这是无用的,因为如果没有发生变异X,所以结果基本上丢弃。 要保留结果,您需要将其分配给某些东西: x = x.Where(filter);
这与使用字符串时的想法是一样的。

 

第二个答案:

有一个内置的代表呼吁Predicate<T>。我认为使用这种类型的运气可能比Func<T, bool>有更多的运气,即使它们本质上具有相同的含义。我认为这是编译器错误想要说的。