Link to home
Start Free TrialLog in
Avatar of karakav
karakav

asked on

How to sort a generic list withouth knowing in advance which property to base the sort

Hi there,
I found this sort that is interesting in sorting a generic list: http://dotnetslackers.com/community/blogs/simoneb/archive/2007/06/20/How-to-sort-a-generic-List_3C00_T_3E00_.aspx. I would like a solution that doesn't require in advance to know which property to use for the sort. Because the solution presented here is not mantainable if the class has many properties.
Avatar of technofile
technofile
Flag of United States of America image

Avatar of karakav
karakav

ASKER

Dear technofile, this link you sent is the one I said it doesn't help for me.
ASKER CERTIFIED SOLUTION
Avatar of Corey_819
Corey_819

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I think this is exactly the case where trying to make something too easy just makes it too complicated and impossible to maintain.

The article is nice but I would advise you to either:
1) you always sort an object on the same property or you want to have a "default" sort behavior: implement the IComparable interface
2) you never know which property to use for the sort:
products.Sort(delegate(Product p1, Product p2)            
 {return p1.ProductName.CompareTo(p2.ProductName);});

honestly, once you get used to how delegates and anonymous methods look like semantically it's really not a big deal having to use this a few places in your code. If you do wish to do something more complicated you can use "dynamic delegates". There's some info here if you wish: http://www.devsource.com/c/a/Languages/Working-with-Delegates-in-C/2/ or go for some reflection as suggested by Corey.
Avatar of karakav

ASKER

Corey,

Would you mind give me a snippet on how to use the reflection to know the property?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of karakav

ASKER

Thanks.