How to execute LINQ OrderBy based on string name for column

If i had

public ActionResult ListExpenseItems(long id)
{
            IQueryable<I_ITEM> expenseItems = er.GetExpenseItems(id);
            return PartialView(expenseItems );
}

and LINQ

public IQueryable<I_ITEM> GetExpenseItems(long id)
{
            return from i in db.I_ITEM
                   where i.ExpenseId == id
                   orderby i.ExpenseItemId ascending
                   select i;
 }

If I passed the string as a parameter to the LINQ method, say "ExpenseTitle", how would I OrderBy i.ExpenseTitlemake orderby always match the string parameter?

Such logic ... but actually correct:

db.I_ITEM.OrderBy(x => (orderBy == 'date') ? x.Date : (orderBy == 'id') ? x.Id : (orderBy == 'cost') ? x.Cost : x.Id);
+3
source share
1 answer

I think these previous questions may solve your problem.

Dynamic LINQ OrderBy

Strong dynamic Linq sorting

or you can use the Dynamic Linq library.

+2
source

Source: https://habr.com/ru/post/1796019/


All Articles