0

I have a function with a LINQ query set up as follows:

public List<company> FetchSortedList(string cat)
{
   var aDTOList = (from s in db.companies
                   where s.category == cat
                   orderby s.name
                   select s).ToList();
}

I now need to change this function to allow the user to pass down another parameter called "field" which will a string value with the name of the property for the list to be sorted by. Is there anyway to do this similar to the above query, i.e.:

 public List<company> FetchSortedList(string cat, string prop)
 {
    var aDTOList = (from s in db.companies
                    where s.category == cat
                    orderby s[prop]
                    select s).ToList();
 }

(I know the above code doesn't work, just asking if there is anything akin to doing something like that)

Or will I need to do something else?

SenTaiyou
  • 117
  • 2
  • 10

1 Answers1

0

You need to construct an Expression that should look like x => x.SomePropertyToSortBy and pass it to OrderBy method.

takemyoxygen
  • 3,951
  • 20
  • 19