0

There is a class Employee, defined below:

class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
}

and I need to fill in the list of expressions, something like below:

var expressions = new List<Expression<Func<Employee, object>>>()
{
    e => e.Id,
    e => e.Name
}

but that should be based on another string which is

var fields = new List<string>() { "Id", "Name" };

So the idea is to fill the expressions list with those fields which are there in the fields string list. Therefore we will search those exact field names in the Employee class and based on that get the property and fill the expressions list.

0

1 Answer 1

2

Figure out how to do this for one property name first.

Expression<Func<Employee, object>> GetExpression(string propertyName) {
    var parameter = Expression.Parameter(typeof(Employee));
    var propertyInfo = typeof(Employee).GetProperty(propertyName);
    if (propertyInfo == null) {
        throw new Exception("No such property!");
    }
    var memberAccess = Expression.Property(parameter, propertyInfo);
    return Expression.Lambda<Func<Employee, object>>(
        propertyInfo.PropertyType.IsValueType ?
            Expression.Convert(memberAccess, typeof(object)) :
            memberAccess, 
        parameter);
}

Note that you will need an Expression.Convert if the type of the property is a value type. This is to box the value into an object.

Then you can just Select the list of names:

List<Expression<Func<Employee, object>>> GetExpressions(List<string> propertyNames) =>
    propertyNames.Select(n => GetExpression(n)).ToList();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.