score:0

Maybe you're looking for something like this:

class Program
{
    static void Main(string[] args)
    {
        Func<Person, bool> isInParis = BuildFunc("Location", "==", "Paris");
        Console.WriteLine(isInParis(new Person { Location = "Paris"})); // Prints true
        Console.WriteLine(isInParis(new Person { Location = "Venice"})); // Prints false
    }

    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public int Weight { get; set; }
        public DateTime FavouriteDay { get; set; }
        public string Location { get; set; }
    }

    private static Func<Person, bool> BuildFunc(
        string propertyName, 
        string comparisonOperator, 
        string propertyValue)
    {
        var parameter = Expression.Parameter(typeof (Person), "person");
        var property = Expression.Property(parameter, propertyName);
        var constant = Expression.Constant(propertyValue);

        Expression comparison;
        switch (comparisonOperator)
        {
            case "<":
                comparison = Expression.LessThan(property, constant);
                break;
            case ">":
                comparison = Expression.GreaterThan(property, constant);
                break;
            default:
                comparison = Expression.Equal(property, constant);
                break;
        }

        return Expression.Lambda<Func<Person, bool>>(comparison, parameter).Compile();
    }
}

Hope it helps!


Related Query

More Query from same tag