Sort a generic list (IList) by ToString() value

For whatever reason, Microsoft didn't provide a Sort method in IList. So it seems like sorting a generic list requires that the list be adapted to an ArrayList. Here's a class and method call that supports sorting any list by the ToString() value of its members.

public class ToStringComparer : IComparer 
{
   public int Compare(object x, object y) 
   {
      return x.ToString().CompareTo(y.ToString());
   }
}

ArrayList.Adapter(list).Sort(new ToStringComparer());

 

Print | posted @ Monday, May 08, 2006 2:27 PM

Comments on this entry:

Gravatar # re: Sort a generic list (IList) by ToString() value
by Josh Einstein at 6/24/2006 11:09 AM

Because IList is just an interface, it can't make assumptions about the data structure that is implementing it. The class might not be sortable (for example, a collection that is optimized to be read in the order of inserts) or the sort parameters may vary.

You can also use List<T> to do what you want.
Gravatar # re: Sort a generic list (IList) by ToString() value
by Andrew at 4/9/2007 8:51 PM

This works great, thanks for the suggestion.
Only thing extra I had to do, to cast my x and y to the object type I was using, in my case IList<T> type's element
Gravatar # re: Sort a generic list (IList) by ToString() value
by Andrew at 4/9/2007 8:51 PM

Code is below for the above comment:

public class ToStringComparer : IComparer
{
public int Compare(object x, object y)
{
return ((FieldEngine)x).FieldName.ToString().CompareTo(((FieldEngine)y).FieldName.ToString());
}
}

public IList<FieldEngine> SortIList(IList<FieldEngine> list)
{
ArrayList.Adapter((IList)list).Sort(new ToStringComparer());

return list;
}
Gravatar # re: Sort a generic list (IList) by ToString() value
by Pete at 10/24/2007 8:35 PM

What about:

((List<BPVersie>)bpPlannen).Sort();

like mentioned in a previous post
Gravatar # re: Sort a generic list (IList) by ToString() value
by jay at 4/16/2008 2:27 PM

I prefer:

-- create sorter derived form icomparer
public class NewsSorter : IComparer<NewsItem>
{
public int Compare(NewsItem x, NewsItem y)
{
return x.CreatedDate.CompareTo(y.CreatedDate);
}
}

// declare and populate my generic news list
List<NewsItem> n1 = NewsItemDA.GetAllNewsList();
// sort it using the sort class
n1.Sort(new NewsSorter());


this gives me the ability to have multiple sorts for the same class.

Gravatar # re: Sort a generic list (IList) by ToString() value
by <>/.asdkl;s;d at 12/16/2008 8:44 PM

<>/.asdkl;s;d

Your comment:

Title:
Name:
Email:
Website:
 
Italic Underline Blockquote Hyperlink
 
 
Please add 2 and 2 and type the answer here: