Linq To SQL: Sort Query by Arbitrary Property(Column) Name

后端 未结 3 1624
没有蜡笔的小新
没有蜡笔的小新 2021-01-11 12:42

I have a larger/more complex problem, but for simplicity sake, let us consider the following:

Let us say that I have table in the SQL DataBase calle

相关标签:
3条回答
  • 2021-01-11 12:52

    You could use Dynamic Linq for this purpose.

    See here Dynamic LINQ (Part 1: Using the LINQ Dynamic Query Library)

    Then you can make calls like this:

    var query = DBContext.Users.Where( "Age > 3" ).OrderBy( "Name asc" );
    
    0 讨论(0)
  • 2021-01-11 13:14

    Try this out instead:

    query.OrderBy(x => x.GetType().GetProperty(“Name”).GetValue(x, null));
    

    You can't just grab the property. You need to grab the value off of that property, hence the call to GetValue.

    0 讨论(0)
  • 2021-01-11 13:15

    It is not as easy as it seems. The LINQ to SQL engine parses the expression you pass to the OrderBy method in order to obtain the name of the property you are referencing, then uses this information to compose a plain SQL order by clause.

    I guess that maybe it can be done by using reflection, anyway. Maybe you can get something useful from the accepted answer of this SO question.

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