realist
realist

Reputation: 2375

Create a method which create dynamic expression

I want to create a method which return dictionary like below. But, I want being generic method which paremerters ara EntityType and columnNameList. I want to call like this,

My method calling:

CreateColumnMap<Student>(new List<string>{"Name","Surname","Age"});

My return value

 var columnsMap = new Dictionary<string, Expression<Func<Student, object>>>()
                    {
                      ["Name"] = v => v.Name,
                      ["Surname"] = v => v.Surname,
                      ["Age"] = v => v.Age
                    };

Student.cs

public class Student
{
    public string Name { get; set; }
    public string Surname { get; set; }
    public string Age { get; set; }
    public string SchoolName { get; set; }
}

I started function like below. But i can't complete. How can i complete "???" part.

public Dictionary<string, Expression<Func<T, object>>> CreateColumnMap<T>(List<string> columNameList)
{
    var dictionary = new Dictionary<string, Expression<Func<T, object>>>();
    foreach (var columnName in columNameList)
    {
        //??????
        dictionary.Add(); //????????????????????
        //??????
    }
    return dictionary;
}

Upvotes: 0

Views: 86

Answers (1)

Nkosi
Nkosi

Reputation: 247018

Reference Creating Expression Trees by Using the API

Use the Expression class and its static factory methods to manually build the desired expression based on the provided member name from the generic argument type.

For example, the following uses the Parameter and Property factory methods to manually build the expression tree nodes for the lambda expression v => v.PropertyName

Expression<Func<TModel, object>> GetPropertyExpression<TModel>(string propertyName) {
    // Manually build the expression tree for 
    // the lambda expression v => v.PropertyName.

    // (TModel v) =>
    var parameter = Expression.Parameter(typeof(TModel), "v");
    // (TModel v) => v.PropertyName
    var property = Expression.Property(parameter, propertyName);

    var expression = Expression.Lambda<Func<TModel, object>>(property, parameter);
    return expression;
}

You can then apply the above

public Dictionary<string, Expression<Func<T, object>>> CreateColumnMap<T>(List<string> columNameList) {
    var dictionary = new Dictionary<string, Expression<Func<T, object>>>();
    foreach (var columnName in columNameList) {            
        dictionary[columnName] = GetPropertyExpression<T>(columnName);
    }
    return dictionary;
}

Upvotes: 3

Related Questions