C# String to LINQ Expression

05 May 2009 by Stuart Cam is my new water cooler.

I had been thinking about writing a small C#-based DSL for a while and was getting hung up on how to express and evaluate expression trees, in particular conditional expressions and predicates. I was aware of the Predicate Builder framework, I have some ANTLR knowledge, so I figured I could write an ANTLR grammar and walk the AST to build a predicate in C#.

My real problem was struggling to find somebody I could talk design with whose eyes wouldn't glaze over after the first 10 seconds.

Cue StackOverflow from stage left.

I posted the question and within 24 hours I'd received two interesting takes on the problem. It appears as though my original plan was probably overbaked and that there was a much simpler solution available.

Code below:

using System;
using System.Linq.Expressions;
using System.Linq.Dynamic;

namespace ExpressionParser
    class Program
        public class Person
            public string Name { get; set; }
            public int Age { get; set; }
            public int Weight { get; set; }
            public DateTime FavouriteDay { get; set; }

        static void Main()
            const string exp = @"(Person.Age > 3 AND Person.Weight > 50) OR Person.Age < 3";
            var p = Expression.Parameter(typeof(Person), "Person");
            var e = DynamicExpression.ParseLambda(new[] { p }, null, exp);
            var bob = new Person
                              Name = "Bob",
                              Age = 30,
                              Weight = 213,
                              FavouriteDay = new DateTime(2000,1,1)
            var result = e.Compile().DynamicInvoke(bob);

Before StackOverflow I really don't know where this interaction could have taken place.

Tags: , , ,

Categories: .NET | C Sharp

© Codebrain 2017. All Rights Reserved. Registered in England: 07744920. VAT: GB 119 4078 13