1

I'm creating a endpoint to retrieve some data from my database, I'm trying to create a custom order by functionallity in my front end so I can call my endpoint with something like this:

https://someapiurl/api/v1/controller/GetItems?ID=1&OrderBy=Name desc

And this is the code that I have in my endpoint:

//This is an example of how I populate my variable which works fine (I have the elements from the database). List is a Iqueryable<ModelName> object.
var list = dbContext.SomeEntity.FindAll...

//Code to get "Name" instead of "Name desc"
var param = orderByQueryString.Split(' ')[0];

if (orderByQueryString.Contains("asc"))
    return list.OrderBy(x => param);
else
    return list.OrderByDescending(x => param);

With both returns I'm getting my list in ascending order. But if I do the following code:

return list.OrderBy(x => x.Name);

Or

return list.OrderByDescending(x => x.Name);

Both works fine so my question is, what can I do to have the orderby element dinamically in that code, because sometimes I'll send Name, sometimes Id or CreatedDate or something like that.

Btw... I tried with list.OrderBy(param); but I got The type arguments for method 'method' cannot be inferred from the usage error message.

User1899289003
  • 850
  • 2
  • 21
  • 40
  • I got could not be translated error message using the code from the answer in the duplicate question. I solve this using Linq.Dynamic nuget package. Now I'm able to cal OrderBy("param desc") – User1899289003 Dec 07 '21 at 06:32

1 Answers1

0

Use this instead

x => x.GetType().GetProperty(param).GetValue(x, null)
DCAggie
  • 144
  • 8
  • I tried your code but returns this error message: could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync' – User1899289003 Dec 07 '21 at 06:20
  • Check this working example and compare to your implementation https://dotnetfiddle.net/BwYx6I – DCAggie Dec 07 '21 at 06:48