Programing

표현 트리의 실제 사용

lottogame 2020. 11. 15. 10:50
반응형

표현 트리의 실제 사용


표현식 트리는 좋은 기능이지만 실제 용도는 무엇입니까? 어떤 종류의 코드 생성이나 메타 프로그래밍 등에 사용할 수 있습니까?


Jon이 언급했듯이, 저는이를 사용 하여 .NET 3.5의 일반 연산자 를 제공합니다 . 또한 기본이 아닌 생성자에 대한 빠른 액세스를 제공하기 위해 (MiscUtil에서 다시) 사용합니다 (생성자 Delegate.CreateDelegate와 함께 사용할 수는 없지만 Expression잘 작동합니다).

수동으로 생성 된 표현식 트리의 기타 용도 :

그러나 실제로 Expression은 동적 코드를 작성하는 매우 다양한 방법입니다. 보다 훨씬 간단 Reflection.Emit하고 내 돈으로는 CodeDOM보다 이해하기 쉽습니다. 그리고 .NET 4.0에서는 더 많은 옵션을 사용할 수 있습니다. Expression 내 블로그 를 통해 코드 작성의 기본 사항을 보여줍니다 .


Marc Gravell은 일반 연산자 를 구현하기 위해 MiscUtil 에서 큰 효과를 내기 위해 이들을 사용했습니다 .


난 그냥 만들어 generic filter function사용 ExpressionTree.. 내가 원하는 share너희들과 함께 ...

Start

var allFiltered= Filter(AllCustomer, "Name", "Moumit");

public static List<T> Filter<T>(this List<T> Filterable, string PropertyName, object ParameterValue)
{
    ConstantExpression c = Expression.Constant(ParameterValue);
    ParameterExpression p = Expression.Parameter(typeof(T), "xx");
    MemberExpression m = Expression.PropertyOrField(p, PropertyName);
    var Lambda = Expression.Lambda<Func<T, Boolean>>(Expression.Equal(c, m), new[] { p });
    Func<T, Boolean> func = Lambda.Compile();
    return Filterable.Where(func).ToList();
}

One More

string singlePropertyName=GetPropertyName((Property.Customer p) => p.Name);

public static string GetPropertyName<T, U>(Expression<Func<T, U>> expression)
{
        MemberExpression body = expression.Body as MemberExpression;
        // if expression is not a member expression
        if (body == null)
        {
            UnaryExpression ubody = (UnaryExpression)expression.Body;
            body = ubody.Operand as MemberExpression;
        }
        return string.Join(".", body.ToString().Split('.').Skip(1));
}

Make it more expandable

string multiCommaSeparatedPropertyNames=GetMultiplePropertyName<Property.Customer>(c => c.CustomerId, c => c.AuthorizationStatus)

public static string GetMultiplePropertyName<T>(params Expression<Func<T, object>>[] expressions)
{
        string[] propertyNames = new string[expressions.Count()];
        for (int i = 0; i < propertyNames.Length; i++)
        {
            propertyNames[i] = GetPropertyName(expressions[i]);
        }

        return propertyNames.Join();
}

....... I know it also can be done using Reflection ... but this one is tremendous fast or i can say equivalent to Lambda after first compilation ... The very first iteration is just an average 10 millisecond slow... So this is Expression Tree magic. Simple and fantastic....I think ...!!!!!!!!


I use them to create dynamic queries, whether it be for sorting or filtering the data. As an example:

IQueryable<Data.Task> query = ctx.DataContext.Tasks;

if (criteria.ProjectId != Guid.Empty)
      query = query.Where(row => row.ProjectId == criteria.ProjectId);

if (criteria.Status != TaskStatus.NotSet)
      query = query.Where(row => row.Status == (int)criteria.Status);

if (criteria.DueDate.DateFrom != DateTime.MinValue)
      query = query.Where(row => row.DueDate >= criteria.DueDate.DateFrom);

if (criteria.DueDate.DateTo != DateTime.MaxValue)
     query = query.Where(row => row.DueDate <= criteria.DueDate.DateTo);

if (criteria.OpenDate.DateFrom != DateTime.MinValue)
     query = query.Where(row => row.OpenDate >= criteria.OpenDate.DateFrom);

var data = query.Select(row => TaskInfo.FetchTaskInfo(row));

Implementation of LINQ providers is mostly done by processing expression trees. I'm also using them to remove literal strings from my code:


I used expression tree to build a math expression evaluator: Building Expression Evaluator with Expression Trees in C#


You can use them to build your own linq provider for a website like Google or Flickr or Amazon, your own website or another data provider.


Originally by Jomo Fisher, Gustavo Guerra published a revised version of the static string dictionary.

Where through Expression trees, a dynamic expression that provides a really (read: ridiculously) Dictionary.

The implementation creates a dynamic decision tree that select the corrent value according to the length of the input string, then by the first letter, then the second letter and so on.

This ultimately runs much faster than the equivalent Dictionary.

참고URL : https://stackoverflow.com/questions/403088/practical-use-of-expression-trees

반응형