3

I would like to extend the expression parameter in my method to add my own filters. I am trying to do something like below, but the syntax is wrong:

public static IList<MyPage> DoSomething<T>(Expression<Func<T, bool>> predicate)
{
    return DataStore().GetPages().Where(p => p.PublishDate < DateTime.Now && predicate)
}

The compiler is complaining is complaining in Visual Studio 2012 with this error:

Error 29 Operator '&&' cannot be applied to operands of type 'bool' and 'System.Linq.Expressions.Expression<System.Func<T,bool>>'

Would extending the predicate first be better then feed if back as .Where(predicate)? How would you do that?

svick
  • 236,525
  • 50
  • 385
  • 514
TruMan1
  • 33,665
  • 59
  • 184
  • 335

1 Answers1

4

Would extending the predicate first be better then feed if back as .Where(predicate)? How would you do that?

Yes, and exactly like that, if I understand what you are suggesting correctly. You can chain .Where() like this:

public static IList<MyPage> DoSomething<T>(Expression<Func<T, bool>> predicate)
{
    return DataStore().GetPages().Where(p => p.PublishDate < DateTime.Now).Where(predicate);
}
  • Yeah, in this specific case (ANDing predicates together), this is the best option. ORing would require something like `PredicateBuilder`. – svick Feb 23 '13 at 09:56
  • The compiler error when I try that is: The best overloaded method match for 'PagesFacade.Where(System.Func)' has some invalid arguments. – TruMan1 Feb 23 '13 at 09:57
  • @svick For completeness, ORing is possible with `.Union()`, but when it gets translated to SQL, and the query gets complex enough, it could perform significantly worse than a real OR. –  Feb 23 '13 at 09:57
  • @TruMan1 Can you include the full message? Also, I now realise this is missing a `.ToList()` at the end (either that, or the return type of `DoSomething` needs a change), but that cannot cause the error you are seeing. –  Feb 23 '13 at 10:00
  • @TruMan1 That sounds like `GetPages()` doesn't return `IQueryable` after all. – svick Feb 23 '13 at 10:01
  • how embarassing.. you're right it returns an IList. Show I convert it to another type? – TruMan1 Feb 23 '13 at 10:15