代码之家  ›  专栏  ›  技术社区  ›  Codebrain

如何将字符串转换为其等效的LINQ表达式树?

  •  150
  • Codebrain  · 技术社区  · 17 年前

    我有一门课叫Person:

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

    var bob = new Person {
      Name = "Bob",
      Age = 30,
      Weight = 213,
      FavouriteDay = '1/1/2000'
    }
    

    我想写以下内容作为参考 一串

    (Person.Age > 3 AND Person.Weight > 50) OR Person.Age < 3
    

    我想用这个字符串和我的对象实例计算真或假-即计算Func<个人,bool>在对象实例上。

    1. 在ANTLR中实现基本语法,以支持基本比较和逻辑运算符。我正在考虑复制Visual Basic优先级和此处的一些功能集: http://msdn.microsoft.com/en-us/library/fw84t893(VS.80).aspx
    2. 让ANTLR从提供的字符串创建合适的AST。
    3. Predicate Builder 动态创建函数的框架<个人,bool>

    我的问题是,我是否完全夸大了这一点?还有别的选择吗?


    我决定使用动态Linq库,特别是LINQSamples中提供的动态查询类。

    代码如下:

    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 = System.Linq.Dynamic.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);
          Console.WriteLine(result);
          Console.ReadKey();
        }
      }
    }
    

    结果的类型为System.Boolean,在本例中为TRUE。

    非常感谢马克·格雷威尔。

    System.Linq.Dynamic here

    6 回复  |  直到 8 年前
        1
  •  69
  •   Erwin Mayer    10 年前

    dynamic linq library 帮帮忙?特别是,我想作为一个 Where 条款如有必要,将其放入列表/数组中以调用 .Where(string) 在上面!即

    var people = new List<Person> { person };
    int match = people.Where(filter).Any();
    

    Expression 我在圣诞节前的火车通勤中写了一篇类似的文章(虽然我不知道来源)。。。

        2
  •  31
  •   Dan Atkinson    14 年前

    另一个这样的图书馆是 Flee

    Dynamic Linq Library 逃走 而逃跑的速度是表情的10倍 "(Name == \"Johan\" AND Salary > 500) OR (Name != \"Johan\" AND Salary > 300)"

    static void Main(string[] args)
    {
      var context = new ExpressionContext();
      const string exp = @"(Person.Age > 3 AND Person.Weight > 50) OR Person.Age < 3";
      context.Variables.DefineVariable("Person", typeof(Person));
      var e = context.CompileDynamic(exp);
    
      var bob = new Person
      {
        Name = "Bob",
        Age = 30,
        Weight = 213,
        FavouriteDay = new DateTime(2000, 1, 1)
      };
    
      context.Variables["Person"] = bob;
      var result = e.Evaluate();
      Console.WriteLine(result);
      Console.ReadKey();
    }
    
        3
  •  9
  •   Amit    8 年前
    void Main()
    {
        var testdata = new List<Ownr> {
            //new Ownr{Name = "abc", Qty = 20}, // uncomment this to see it getting filtered out
            new Ownr{Name = "abc", Qty = 2},
            new Ownr{Name = "abcd", Qty = 11},
            new Ownr{Name = "xyz", Qty = 40},
            new Ownr{Name = "ok", Qty = 5},
        };
    
        Expression<Func<Ownr, bool>> func = Extentions.strToFunc<Ownr>("Qty", "<=", "10");
        func = Extentions.strToFunc<Ownr>("Name", "==", "abc", func);
    
        var result = testdata.Where(func.ExpressionToFunc()).ToList();
    
        result.Dump();
    }
    
    public class Ownr
    {
        public string Name { get; set; }
        public int Qty { get; set; }
    }
    
    public static class Extentions
    {
        public static Expression<Func<T, bool>> strToFunc<T>(string propName, string opr, string value, Expression<Func<T, bool>> expr = null)
        {
            Expression<Func<T, bool>> func = null;
            try
            {
                var type = typeof(T);
                var prop = type.GetProperty(propName);
                ParameterExpression tpe = Expression.Parameter(typeof(T));
                Expression left = Expression.Property(tpe, prop);
                Expression right = Expression.Convert(ToExprConstant(prop, value), prop.PropertyType);
                Expression<Func<T, bool>> innerExpr = Expression.Lambda<Func<T, bool>>(ApplyFilter(opr, left, right), tpe);
                if (expr != null)
                    innerExpr = innerExpr.And(expr);
                func = innerExpr;
            }
            catch (Exception ex)
            {
                ex.Dump();
            }
    
            return func;
        }
        private static Expression ToExprConstant(PropertyInfo prop, string value)
        {
            object val = null;
    
            try
            {
                switch (prop.Name)
                {
                    case "System.Guid":
                        val = Guid.NewGuid();
                        break;
                    default:
                        {
                            val = Convert.ChangeType(value, prop.PropertyType);
                            break;
                        }
                }
            }
            catch (Exception ex)
            {
                ex.Dump();
            }
    
            return Expression.Constant(val);
        }
        private static BinaryExpression ApplyFilter(string opr, Expression left, Expression right)
        {
            BinaryExpression InnerLambda = null;
            switch (opr)
            {
                case "==":
                case "=":
                    InnerLambda = Expression.Equal(left, right);
                    break;
                case "<":
                    InnerLambda = Expression.LessThan(left, right);
                    break;
                case ">":
                    InnerLambda = Expression.GreaterThan(left, right);
                    break;
                case ">=":
                    InnerLambda = Expression.GreaterThanOrEqual(left, right);
                    break;
                case "<=":
                    InnerLambda = Expression.LessThanOrEqual(left, right);
                    break;
                case "!=":
                    InnerLambda = Expression.NotEqual(left, right);
                    break;
                case "&&":
                    InnerLambda = Expression.And(left, right);
                    break;
                case "||":
                    InnerLambda = Expression.Or(left, right);
                    break;
            }
            return InnerLambda;
        }
    
        public static Expression<Func<T, TResult>> And<T, TResult>(this Expression<Func<T, TResult>> expr1, Expression<Func<T, TResult>> expr2)
        {
            var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
            return Expression.Lambda<Func<T, TResult>>(Expression.AndAlso(expr1.Body, invokedExpr), expr1.Parameters);
        }
    
        public static Func<T, TResult> ExpressionToFunc<T, TResult>(this Expression<Func<T, TResult>> expr)
        {
            var res = expr.Compile();
            return res;
        }
    }
    

    LinqPad Dump() 方法

        4
  •  5
  •   Darin Dimitrov    17 年前

    你可以看一下 DLR IronRuby :

    using System;
    using IronRuby;
    using IronRuby.Runtime;
    using Microsoft.Scripting.Hosting;
    
    class App
    {
        static void Main()
        {
            var setup = new ScriptRuntimeSetup();
            setup.LanguageSetups.Add(
                new LanguageSetup(
                    typeof(RubyContext).AssemblyQualifiedName,
                    "IronRuby",
                    new[] { "IronRuby" },
                    new[] { ".rb" }
                )
            );
            var runtime = new ScriptRuntime(setup);
            var engine = runtime.GetEngine("IronRuby");
            var ec = Ruby.GetExecutionContext(runtime);
            ec.DefineGlobalVariable("bob", new Person
            {
                Name = "Bob",
                Age = 30,
                Weight = 213,
                FavouriteDay = "1/1/2000"
            });
            var eval = engine.Execute<bool>(
                "return ($bob.Age > 3 && $bob.Weight > 50) || $bob.Age < 3"
            );
            Console.WriteLine(eval);
    
        }
    }
    
    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public int Weight { get; set; }
        public string FavouriteDay { get; set; }
    }
    

        5
  •  1
  •   ncaralicea    13 年前

    下面是一个基于Scala DSL的解析器组合器示例,用于解析和计算算术表达式。

    import scala.util.parsing.combinator._
    /** 
    * @author Nicolae Caralicea
    * @version 1.0, 04/01/2013
    */
    class Arithm extends JavaTokenParsers {
      def expr: Parser[List[String]] = term ~ rep(addTerm | minusTerm) ^^
        { case termValue ~ repValue => termValue ::: repValue.flatten }
    
      def addTerm: Parser[List[String]] = "+" ~ term ^^
        { case "+" ~ termValue => termValue ::: List("+") }
    
      def minusTerm: Parser[List[String]] = "-" ~ term ^^
        { case "-" ~ termValue => termValue ::: List("-") }
    
      def term: Parser[List[String]] = factor ~ rep(multiplyFactor | divideFactor) ^^
        {
          case factorValue1 ~ repfactor => factorValue1 ::: repfactor.flatten
        }
    
      def multiplyFactor: Parser[List[String]] = "*" ~ factor ^^
        { case "*" ~ factorValue => factorValue ::: List("*") }
    
      def divideFactor: Parser[List[String]] = "/" ~ factor ^^
        { case "/" ~ factorValue => factorValue ::: List("/") }
    
      def factor: Parser[List[String]] = floatingPointConstant | parantExpr
    
      def floatingPointConstant: Parser[List[String]] = floatingPointNumber ^^
        {
          case value => List[String](value)
        }
    
      def parantExpr: Parser[List[String]] = "(" ~ expr ~ ")" ^^
        {
          case "(" ~ exprValue ~ ")" => exprValue
        }
    
      def evaluateExpr(expression: String): Double = {
        val parseRes = parseAll(expr, expression)
        if (parseRes.successful) evaluatePostfix(parseRes.get)
        else throw new RuntimeException(parseRes.toString())
      }
      private def evaluatePostfix(postfixExpressionList: List[String]): Double = {
        import scala.collection.immutable.Stack
    
        def multiply(a: Double, b: Double) = a * b
        def divide(a: Double, b: Double) = a / b
        def add(a: Double, b: Double) = a + b
        def subtract(a: Double, b: Double) = a - b
    
        def executeOpOnStack(stack: Stack[Any], operation: (Double, Double) => Double): (Stack[Any], Double) = {
          val el1 = stack.top
          val updatedStack1 = stack.pop
          val el2 = updatedStack1.top
          val updatedStack2 = updatedStack1.pop
          val value = operation(el2.toString.toDouble, el1.toString.toDouble)
          (updatedStack2.push(operation(el2.toString.toDouble, el1.toString.toDouble)), value)
        }
        val initial: (Stack[Any], Double) = (Stack(), null.asInstanceOf[Double])
        val res = postfixExpressionList.foldLeft(initial)((computed, item) =>
          item match {
            case "*" => executeOpOnStack(computed._1, multiply)
            case "/" => executeOpOnStack(computed._1, divide)
            case "+" => executeOpOnStack(computed._1, add)
            case "-" => executeOpOnStack(computed._1, subtract)
            case other => (computed._1.push(other), computed._2)
          })
        res._2
      }
    }
    
    object TestArithmDSL {
      def main(args: Array[String]): Unit = {
        val arithm = new Arithm
        val actual = arithm.evaluateExpr("(12 + 4 * 6) * ((2 + 3 * ( 4 + 2 ) ) * ( 5 + 12 ))")
        val expected: Double = (12 + 4 * 6) * ((2 + 3 * ( 4 + 2 ) ) * ( 5 + 12 ))
        assert(actual == expected)
      }
    }
    

    提供的算术表达式的等效表达式树或解析树将是Parser[List[String]]类型。

    有关更多详细信息,请访问以下链接:

    http://nicolaecaralicea.blogspot.ca/2013/04/scala-dsl-for-parsing-and-evaluating-of.html

        6
  •  0
  •   Vitaliy Fedorchenko    12 年前

    NReco Commons Library (开源)。它在运行时对齐所有类型并执行所有调用,其行为类似于动态语言:

    var lambdaParser = new NReco.LambdaParser();
    var varContext = new Dictionary<string,object>();
    varContext["one"] = 1M;
    varContext["two"] = "2";
    
    Console.WriteLine( lambdaParser.Eval("two>one && 0<one ? (1+8)/3+1*two : 0", varContext) ); // --> 5
    
        7
  •  0
  •   Roi Shabtai    6 年前

    虽然这是相对较旧的post-这是expression builder的代码: AnyService - ExpressionTreeBuilder AnyService - ExpressionTreeBuilder Unit Tests

    推荐文章