I have an ArrayList of objects that I need to sort in two different fashions, depending on the situation. I followed this example: http://codebetter.com/blogs/david.hayden/archive/2005/03/06/56584.aspx on how to create a PersonComparer by overloading the IComparer object. I liked this method because it allowed me to build an enumerator of sort criteria that I could set on the fly.
However, when I convert my ArrayList to the generic List<T> type, this method no longer works. When I try to pass my “comparer” object, I get the following error:
“The best overloaded method match for ‘System.Collections.Generic.List.Sort has some invalid arguments”
My question is: what do I need to change to make this method work? Or more importantly, is there a better way to create multiple custom sorts using Generic lists?
List<T>.Sort() takes has an overload that takes an IComparer<T>, List<T>.Sort(IComparer<T>).
IComparer<T>is just likeIComparer, but it’s strongly typed.To get your code to compile, you need to change your
IComparerimplementation to also implementIComparer<T>. For example, if you have aList<Person>, then your comparer needs to implementIComparer<Person>. For example: