0

I realize this question has been asked many times, but there doesn't seem to be an updated answer using plain old reflection. I am trying to implement sorting into a WebAPI method by using reflection to retrieve the property sent in the "sortBy" parameter. Then I would like to call OrderBy or OrderByDescending according to the value of the "sortOrder" parameter.

Is using a lambda extension method the only way to achieve sorting by a property dynamically?

The accepted answer on this post had a really easy way of retrieving the property dynamically and then getting the value in the OrderBy/OrderByDescending call: How do I specify the Linq OrderBy argument dynamically?

However, this does not seem to work in .NET 6... It errors out and say it either can't be translated unless switched to client evaluation using an enumerable type or can't be cast when adding "AsEnumerable()" to the call.

//Sort products by user provided query
if (!string.IsNullOrEmpty(queryParameters.SortBy))
{
    if(typeof(Product).GetProperty(queryParameters.SortBy) != null)
    {
         //Use reflection to get the sortBy property
         var productPropInfo = typeof(Product).GetProperty(queryParameters.SortBy);
         switch (queryParameters.SortOrder)
         {
              case "desc":
                 //Can't be translated
                 products = products.OrderByDescending(p => productPropInfo.GetValue(p));
                 break;
              default:
                 //Can't be cast when explicitly casting or using AsQueryable()
                 products = products.AsEnumerable().OrderBy(p => productPropInfo.GetValue(p)).AsQueryable();
                 break;
          }
     }
}

Am I missing something? Or do I need to use a lambda extension method like in the link above?

NOTE: I am using an in memory database and Entity Framework Core

Thanks!

  • 1
    If by lambda extension method you mean an `Expression` like in [this answer](https://stackoverflow.com/a/7265354/3034273), then why don't you want to use that solution? EF Core works with expressions to translate it into a database query, so that's kinda the only way unless you want to do client evaluation. – Xerillio Aug 14 '22 at 10:17
  • That answer only works with Linq To Objects. To translate it to SQL it cannot use reflection. One option is to simply have a `Dictionary, IQueryable>>>` which holds various different properties to sort by. – Charlieface Aug 14 '22 at 10:19
  • Does this answer your question? [Order by dynamic parameter](https://stackoverflow.com/questions/65849281/order-by-dynamic-parameter) – Svyatoslav Danyliv Aug 14 '22 at 11:12
  • @Xerillio I just figured if I could use less code, I'd rather go that route. Doesn't seem like it's possible in this case however. – jdelgado1025 Aug 14 '22 at 19:08

0 Answers0