-1

I have the following tuple:

Tuple<Expression<Func<Client, object>>, SortOrder>(x => x.ClientLastName, SortOrder.Descending)

In this case I know the entity - "Client" and you are using the "ClientLastName" column.. x => x.ClientLastName.

I want to change this to a generic version where entity is T and I supply the column name using the value keyValue.Key... eg keyValue.Key in this case = "ClientLastName".

I tried this:

        foreach (KeyValuePair<string, SortDirection> keyValue in sortItems) {
            tupleList.Add(new Tuple<Expression<Func<T, object>>, SortDirection>(x => keyValue.Key, keyValue.Value));
        };

Even though T is Client and keyValue.Key is the column name "ClientLastName"

enter image description here

it doesnt work.. It simply comes up with:

enter image description here

It is not replacing the value of keyValue.Key and instead is using the actual value..

saw this answer by sstan in which he used

d => "value" == (string)typeof(Demo).GetProperty(propname).GetValue(d))

which I changed to:

Tuple<Expression<Func<T, object>>, SortDirection>(x => (string)typeof(T).GetProperty(keyValue.Key).GetValue(x), keyValue.Value));

Which didnt work.

How do I do this x => x.keyValue.Key where it replaces the keyValue.Key with its string value and I can have the equivalent of x => x.ClientLastName?

1 Answer 1

2

Dynamically build the desired expression and pass it to the tuple

Tuple<Expression<Func<T, object>>, SortDirection> BuildTuple<T>(KeyValuePair<string, SortDirection> keyValue) {
    var type = typeof(T);
    var propertyInfo = type.GetProperty(keyValue.Key);
    var direction = keyValue.Value;

    // T x
    var parameter = Expression.Parameter(type, "x");
    // x.Property
    var property = Expression.Property(parameter, propertyInfo);
    // T x => x.Property
    var expression = Expression.Lambda<Func<T, object>>(property, parameter);

    return new Tuple<Expression<Func<T, object>>, SortDirection>(expression, direction);
}

Generic version of the loop becomes

foreach (KeyValuePair<string, SortDirection> keyValue in sortItems) {
    var tuple = BuildTuple<T>(keyValue);
    tupleList.Add(tuple);
};

assuming it is within a generic method.

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.