Dynamic where condition on anonymous object

Viewed 54

I would like to implement method with input like this:

public async Task<IList<T>> Get(Expression<Func<Class1, Class2, Class3, bool>> predicate)
{ 
   var query = from c1 in db.Class1
               from c2 in db.Class2
               from c3 in db.Class3
               select new { c1, c2, c3 };

  return query.Where(predicate).ToListAsync();

}

I want call this method like Get((x, y, z) => x.Prop1 == 1 && y.Prop5 == 4)

I've got error:

Error CS1503 Argument 2: cannot convert from 'System.Linq.Expressions.Expression<System.Func<Class1, Class2, Class3, bool>>' to 
'System.Linq.Expressions.Expression<System.Func<<anonymous type: Class1 pcp, Class2 pc, Class3 bu>, bool>>'

in line containing Where(predicate)

How to I solve this issue ?

1 Answers

Since it isn't possible to have your Get method return the anonymous type and you don't pass the anonymous type in (e.g. with an answer constructor Expression for type inference), you can't use an anonymous type for your query.

Instead create an explicit type and use that for both:

public class CAns {
    public Class1 c1;
    public Class2 c2;
    public Class3 c3;
}

async Task<IList<CAns>> Get(Expression<Func<CAns, bool>> predicate)
{
   var query = from c1 in db.Class1
               from c2 in db.Class2
               from c3 in db.Class3
               select new CAns { c1 = c1, c2 = c2, c3 = c3 };

  return query.Where(predicate).ToListAsync();
}

Then you can call Get with:

var ans = Get(q => q.c1.Prop1 == 1 && q.c2.Prop5 == 4);
Related