1

I wonder if you can do something like this:

    public List<T> FindOrder<T>(Expression<Func<T, bool>> predicate) where T : class
    {
        DbSet<Preventivos> preventivos = this.Preventivos;

        return (from p in preventivos
                where predicate
                select new...
1
  • of course preventivos.Where(predicate).Select(e => new ...) Commented May 7, 2015 at 13:59

3 Answers 3

4

Not like that, no - but you can write:

return preventivos.Where(predicate).Select(...);

... although your code example seems to be unclear as to whether this is really generic or whether it only deals with Preventivos.

The point is that the query expression you've provided would add an extra "wrapper" layer:

return preventivos.Where(p => predicate)
                  .Select(p => new { ... });

... whereas you want to pass the predicate expression tree directly to the Where call.

Sign up to request clarification or add additional context in comments.

2 Comments

but, this way not? from p in preventivos where predicate select new
@EleazarCelis He already answered that question. It's right in the first half sentence.
0

Not with an Expression. If your parameter were just a Func<T, bool> then you could treat predicate as a delegate:

     return (from p in preventivos
            where predicate(p)
            select new ...

Which will probably fail when the provider tries to convert to SQL since it needs have the metadata of an Expression to generate the equivalent SQL.

You could try to Compile the expression first to convert it to a Func<T, bool>:

    return (from p in preventivos
            where predicate.Compile()(p)
            select new ...

Which will compile but may still fail at runtime when the query provider tries to convert it to SQL.

So unless you're really hung up on using query syntax, method syntax would be much cleaner:

return preventivos.Where(predicate)
                  .Select(p => new ...);

Comments

0

To complement Jon's answer, here's a selection from some actual working code (in use @ www.NJtheater.com) allowing you to look a venue by ID# or name

    public void Display(int id)
    {
        Display(ven => ven.VenueID == id);
    }

    public void Display(string name)
    {
        Display(ven => ven.Shortname == name);
    }

    public void Display(Expression<Func<Venue, bool>> whereClause)
    {
        Venue venue = db.Venues.Where(whereClause).FirstOrDefault();

           /// etc

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.