는 방법을 변환할 문자열을 해당하는 LINQ 식 나무입니까?
문제
이것은 단순화된 버전의 원래 문제입니다.
내가 있는 클래스라는 사람은:
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<Person, bool=""> 에 객체를 인스턴스입니다.
여기에는 현재 생각:
- 구현을 기본 문법에 ANTLR 을 지원하는 기본적인 비교하고 논리 연산자입니다.나는 생각하고를 복사하 Visual 기본적인 우선 순위와의 일부 featureset 여기: http://msdn.microsoft.com/en-us/library/fw84t893(VS.80).aspx
- 가 ANTLR 만들기에 적합 AST 에서 제공하는 문자열입니다.
- 보 AST 사용 조건자 Builder framework 를 동적으로 만들 Func<Person, bool="">
- 을 평가하는 조건자 인스턴스에 대해 사람으로 필요
나의 질문은야 나는 완전히 overbaked 이?어떤 대안은?
편집:선택 솔루션
기로 결정했을 사용하여 동적 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();
}
}
}
그 결과 유형 시스템입니다.부울에서 이를 사실이다.
많은 감사를 마크 Gravell.
함 시스템입니다.Linq.동 nuget 패키지 설명서 기
해결책
것 동적 linq 라이브러리 여기에 도움이 될?특히,나는 생각으로 Where
절입니다.필요한 경우에 넣어 나열/배열 전화하기 .Where(string)
니다.즉
var people = new List<Person> { person };
int match = people.Where(filter).Any();
하지 않을 경우 작성,파서(사용 Expression
후드)지 않은 상당히 부담-썼와 유사한(하지만 나는 생각하지 않는 소스)에서 기차로 출퇴근을 하기 전에 그냥 크리스마스...
다른 팁
다른 그러한 라이브러리 피
했다 빠르게 비교 동적 Linq 라이브러리 고 피 고 도망했다 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();
}
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()
방법
수도 있습 살펴보 DLR.그것은 당신을 평가하고 실행하는 스크립트 내부입니다.NET2.0 응용 프로그램.여기 샘플 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; }
}
물론 이 기술을 기반으로 런타임을 평가하고 코드를 확인할 수 없습은 컴파일때 정해진다.
여기의 예로는 스칼라 DSL 기반 parser 연결자에 대한 분석 및 평가를 산술의 표현입니다.
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)
}
}
해당하는 표현이 나무 또는 구문 분석의 나무를 제공하는산 식은 다음과 같습니다의 파서[목록[String]]형식입니다.
더 많은 정보는 다음 링크에서:
http://nicolaecaralicea.blogspot.ca/2013/04/scala-dsl-for-parsing-and-evaluating-of.html
또한 동적 Linq 라이브러리(건설하는 강력한 표현하고 필요한 강력한 형식 변수)추천 더 나은 대안이 있다:linq 파서는 그 부분의 NReco 리에이티브 커먼즈 라이브러리 (오픈 소스).맞춰 모든 종류와 수행하는 모든 호출에 런타임과 같이 행동하는 동적 언어:
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