Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
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 10:49am

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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 at 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ő at 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)

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 450
1 OriginalGriff 220
2 DamithSL 130
3 Dave Kreskowiak 120
4 Suvendu Shekhar Giri 110
0 OriginalGriff 7,645
1 DamithSL 5,614
2 Sergey Alexandrovich Kryukov 5,344
3 Maciej Los 4,961
4 Kornfeld Eliyahu Peter 4,539


Advertise | Privacy | Mobile
Web04 | 2.8.141223.1 | Last Updated 13 Dec 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100