Let's say I've created some anonymous type via a LINQ query:
var query = from Person in db.People
join Pet in Pets on Person.ID equals Pet.PersonID
join Thingy in Thingies on Person.ID equals Thingy.PersonID
select new {
Person.ID,
PetName = Pet.Name,
Thing = Thingy.Thing,
OtherThing = Thingy.OtherThing
};
Now I want to apply some complex expressions to the query by dynamically building a predicate. What I have been doing for known types is something like this:
var predicate = PredicateBuilder.False<MyType>();
predicate = predicate.Or(myType => myType.Flag);
if (someCondition) {
var subPredicate = PredicateBuilder.True<MyType>();
subPredicate = subPredicate.And(myType => myType.Thing == someThing);
subPredicate = subPredicate.And(myType => myType.OtherThing == someOtherThing);
predicate = predicate.Or(subPredicate);
}
query = query.Where(predicate);
Is it possible to do something similar with an anonymous type? I haven't found a way of using anonymous types with PredicateBuilder
and I'm not familiar with any other constructs which would let me dynamically build an expression like this. If not, is there another approach I should take when dynamically generating nested expressions for a query?