3

If I had

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

and the 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 a string in as a parameter to the LINQ method, say "ExpenseTitle", how would I do OrderBy i.ExpenseTitle so that orderby always matches the string parameter?

This kind of logic.. but actually correct:

db.I_ITEM.OrderBy(x => (orderBy == 'date') ? x.Date : (orderBy == 'id') ? x.Id : (orderBy == 'cost') ? x.Cost : x.Id);
tereško
  • 56,151
  • 24
  • 92
  • 147
Chris
  • 3,093
  • 4
  • 20
  • 37
  • Possible duplicate of [How do I specify the Linq OrderBy argument dynamically?](http://stackoverflow.com/questions/7265186/how-do-i-specify-the-linq-orderby-argument-dynamically) – Michael Freidgeim Mar 16 '17 at 07:39

1 Answers1

2

I think this previous questions might solve your problem

Dynamic LINQ OrderBy

Strongly typed dynamic Linq sorting

or you can use the Dynamic Linq library.

Community
  • 1
  • 1
gcores
  • 11,553
  • 1
  • 44
  • 38
  • Both those links go to the same question. I think the second one is looking for this: http://stackoverflow.com/q/557819/2449863 – DCShannon Sep 14 '15 at 20:54