Building an OrderBy Lambda expression based on child entity's property

后端 未结 5 1740
渐次进展
渐次进展 2020-12-10 04:34

I\'m trying to generate a LINQ OrderBy clause using lambda expressions with an input of the column name of an entity as a string (in the \"sortOn\" variable bel

5条回答
  •  萌比男神i
    2020-12-10 05:04

    You can use the Dynamic LINQ Query Library to do this easily. Assuming you have an IQueryable implementation of Product, you can easily do:

    IQueryable products = ...;
    
    // Order by dynamically.
    products = products.OrderBy("Category.Description");
    

    The blog post has a link to the libary, and you'll have to build/include the project in your solution yourself, but it works very well, and the parsing is very robust. It prevents you from having to write the parsing code yourself; even for something so simple, if the requirements expand, the library has you covered, whereas a homegrown solution does not.

    It also has a number of other dynamic operators (Select, Where, etc.) so you can perform other dynamic operations.

    There's no magic under the hood, it just parses the strings you pass it and then creates the lambda expressions based on the parsing results.

提交回复
热议问题