0

I have a interface in that user indicates some elements and operators between them and I should display the result.

User can build then a filter like p1 OP v1 OR p2 OP v2 where p1 and p2 are Person properties, like Age, Name, Location etc, v1 and v2 are comparative values(10, 'Maria', 'L.A.'), OP are comparison operators (=, <, >) and OR is a logical operator(can be also AND).

Eg:
Age > 18 AND Location = 'Paris', or another one like
Name Contains 'andro' AND Sex = 'm'

Having myPeople collection and this filter string, how can I Build and apply this expression using Linq.Expressions?

I tried to use DynamicLinq, but actually I have a problem using "Where" on List<Person>, apparently is not IQueryable...

1 Answer 1

1

If you're trying to use it with List<T>, I wouldn't bother using expression trees to start with:

public static Func<T, bool> Or<T>(Func<T, bool> predicate1,
                                  Func<T, bool> predicate2)
{
    return t => predicate1(t) || predicate2(t);
}

public static Func<T, bool> And<T>(Func<T, bool> predicate1,
                                   Func<T, bool> predicate2)
{
    return t => predicate1(t) && predicate2(t);
}

Then you can do:

Func<Person, bool> isAdult = person => person.Age > 18;
Func<Person, bool> isInParis = person => person.Location == "Paris";

var personInParis = And(isAdult, isInParis);

For the equivalent for expression trees if you want those later, look at PredicateBuilder.

The tricky bit is likely to be converting your string into an expression tree to start with.

If Dynamic LINQ does everything else you want, you can just use AsQueryable to create an IQueryable<T> from an IEnumerable<T>.

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

2 Comments

the problem is in the real project number of predicates is unknown - the user can add filters how many it wants. So, what should I do finally with this var adultPersonInParis, apply it in a Where clause?
@serhio: Just keep building a predicate - start off with something which always returns true, and apply AND and OR appropriately. Look at the PredicateBuilder link for more details - the above is the same idea, just applied to delegates instead of expression trees.

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.