I have an IList<T> that I need to sort, and I would rather not copy the list if possible. I’ve noticed that ArrayList has an Adapter static method that wraps the passed list without copying it, but this takes an IList and I have an IList<T>. Is it safe to cast from a System.Collections.Generic.IList<T> to a System.Collections.IList and just use the Adapter method?
Note that this is .Net 2.0, so LINQ is not an option.
From the blog of Paul Fox, I recommend the post ‘How to sort an IList’: http://foxsys.blogspot.com/2007/06/how-to-sort-generic-ilist.html
Just in case that blog goes away in the future, I’ll copy the post here:
How to sort a generic IList
Update
You can read and updated post about sorting generic IList and List. Many people will prefer the methods mentioned in the updated post.
Sorting a generic IList
I was trying to sort a generic IList<> and found a fairly simple way of doing it.
Step 1
You need to implement IComparable for the type contained in your IList. For this example I am going to use a simple Language Dto class.
STEP 2
Sort your IList. To do this you will use the ArrayList.Adapter() method passing in your IList, and then calling the Sort method. Like so…
Note: languages is of type ‘IList’
Languages should then be a sorted list of your type!