基于字符串为OrderBy创建lambda表达式

时间:2017-10-01 16:46:20

标签: c# .net linq lambda

方法MyMethod作为字符串参数。根据此参数的值,我希望找回一个与OrderBy一起使用的表达式。我找不到Expression<Func<>>使用字典的正确语法(TValue类型)

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)......

}

更新:

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

谢谢,

1 个答案:

答案 0 :(得分:1)

我想你可能会得到一些暗示:

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);
}