dynamically create lambdas expressions + linq + OrderByDescending

前端 未结 2 1276
别那么骄傲
别那么骄傲 2021-01-21 15:24

how can I create a dynamic lambda expression to pass to use in my orderby function inside linq?

I basically want transform queryResults.OrderByDescending();

相关标签:
2条回答
  • 2021-01-21 16:02

    See Dynamic LINQ

    Alternately, you can use a switch statement, Reflection or the dynamic type in C# 4 to return the value based on a supplied field name.

    This has also been done to death previously

    0 讨论(0)
  • 2021-01-21 16:06

    I'm not sure where exactly did you need dynamic lambda expressions. Anyways, the best way to generate lambda expressions dynamically is by using expression trees. Here are two good tutorials on the subject:

    • http://marlongrech.wordpress.com/2008/01/08/working-with-expression-trees-part-1/
    • http://www.davidhayden.com/blog/dave/archive/2006/12/18/ExpressionTrees.aspx [dead link]

    This code generates a lambda expression like the one you asked for ("x => x.name"):

    MemberInfo member = typeof(AClassWithANameProperty).GetProperty("Name");
    
    //Create 'x' parameter expression
    ParameterExpression xParameter = Expression.Parameter(typeof(object), "x");
    
    //Create body expression
    Expression body = Expression.MakeMemberAccess(targetParameter, member);
    
    //Create and compile lambda
    var lambda = Expression.Lambda<LateBoundGetMemberValue>(
        Expression.Convert(body, typeof(string)),
        targetParameter
    );
    return lambda.Compile();
    

    hope this helps

    0 讨论(0)
提交回复
热议问题