Click here to Skip to main content
15,501,490 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a List<MyObjecT> that I would like to be able to sort at run-time. I wanto to do this, without the giant IF statement

private List<Customer> SortCustomer(string sortBy, string sortOrder)
   // obviously I get this from a service in the real code
   var myList = new List<Customer>();

   if (sortBy == "firstname" && sortOrder == "asc") {
       return myList.OrderBy(x => x.FirstName);
   } else if (sortBy == "firstname" && sortOrder == "desc") {
       return myList.OrderByDesc(x => x.firstName);
   } else if ..... // you get the idea


I can't sort in the database easily (one of the fields is a decimal stored as string, another is a lookup field, but there's no lookup table so in the database it is just an int field with no reference. I didn't want to deal with trying to convert the db fields as necessary to sort.

I also can't use the Dynamic Linq Library, just to make things more complicated.

Any ideas?


1 solution

You could write your own comparer implementing IComparer[^]. Here is an example:[^]

Just code all your cases in the comparer, and pass the parameters to be used (property name, order) in the constructor. You can use basic reflection to access properties based on their name. But I am not sure, that you will gain much - but clearer code at least.
Share this answer
AnalogNerd 13-Dec-12 16:32pm    
Thanks, that worked like a charm. The link was really useful as I have never done anything with IComparer before.
Zoltán Zörgő 14-Dec-12 5:10am    
You are welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900