Kris-I Kris-I - 3 years ago 185
C# Question

Create lambda expression for OrderBy based on string

The method

MyMethod
as a string parameter. Based on the value of this parameter, I'd like get back an expression to use with an
OrderBy
. I don't find the right syntax for
Expression<Func<>>
to use with the dictionary (as
TValue
type)

public void MyMethod(string orderBy)
{
var dico = new Dictionary<string, string>
{
{ "property1", x => x.Name},
{ "property2", x => x.Age},
};

dico.TryGetValue("property1", out string myOrder);

myList.OrderBy(myOrder)......

}


Update :

var dico = new Dictionary<string, Expression<Func<Person, xxxxx>>>
{
{ "property1", x => x.Name},
{ "property2", x => x.Age},
};


Thanks,

Answer Source

I think you may get hints from this:

public void MyMethod(string orderBy)
{
    // Assuming Product has 'Name' and 'Age' property ?
    var dico = new Dictionary<string, Expression<Func<Product,object>>>
    {
        { "property1", x => x.Name},
        { "property2", x => x.Age},
    };

    Expression<Func<Product,object>> myorder;
    dico.TryGetValue(orderBy, out myOrder);

    _context.Products.OrderBy(myOrder);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download