-->

Build a simple Expression Tree in .NET

2019-08-30 17:56发布

问题:

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:

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>.