Click here to Skip to main content
Sign Up to vote bad
good
See more: C#LINQ
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?
 
Thanks,
Andrew
Posted 13 Dec '12 - 9:49


1 solution

You could write your own comparer implementing IComparer[^]. Here is an example: http://www.atlanticbt.com/blog/sorting-with-linq-to-objects/[^]
 
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.
  Permalink  
Comments
Andrew Stoute - 13 Dec '12 - 16:32
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:10
You are welcome!

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

  Print Answers RSS
Your Filters
Interested
Ignored
     
0 Sergey Alexandrovich Kryukov 8,356
1 OriginalGriff 6,571
2 CPallini 3,533
3 Rohan Leuva 2,703
4 Maciej Los 2,234


Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 13 Dec 2012
Copyright © CodeProject, 1999-2013
All Rights Reserved. Terms of Use
Layout: fixed | fluid