简体   繁体   中英

C# Linq expressions using the string value of a variable to set the column name in a lambda expression

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"

在此处输入图片说明

it doesnt work.. It simply comes up with:

在此处输入图片说明

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM