Friday, June 01, 2007

How to sort a generic IList<T>

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.
public class LanguageDto : IComparable {
private String name;
public string Name { get { return name; } set { name = value; } }

public LanguageDto(string name) {
this.name = name;
}

#region IComparable Members
public int CompareTo(object obj) {
if (obj is LanguageDto) {
LanguageDto language = (LanguageDto)obj;
return this.name.CompareTo(language.name);
}
throw new ArgumentException(string.Format("Cannot compare a LanguageDto to an {0}", obj.GetType().ToString()));
}
#endregion
}

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...

ArrayList.Adapter((IList)languages).Sort();
Note: languages is of type "IList<LanguageDto>"
Languages should then be a sorted list of your type!

15 comments:

  1. Good One! Helped us a lot. Thanks.

    ReplyDelete
  2. Anonymous3:50 PM

    Thanks, I needed that.

    ReplyDelete
  3. Anonymous8:00 AM

    Thanks! Helped me too...
    Regards

    ReplyDelete
  4. Anonymous12:39 PM

    Thanks! Quick and easy!

    ReplyDelete
  5. Anonymous4:02 PM

    Thanks
    helped me too

    ReplyDelete
  6. This comment has been removed by the author.

    ReplyDelete
  7. Anonymous6:21 PM

    Great post!

    ReplyDelete
  8. Anonymous8:18 AM

    Thanks a lot ! It's exactly what I'm lookin' for :)

    ReplyDelete
  9. Anonymous7:07 AM

    Cool. Exactly what I was looking for. Thanks!

    ReplyDelete
  10. Anonymous7:09 AM

    Consequently, I was tipped off to your post from StackOverflow.com.

    http://stackoverflow.com/questions/226981/what-is-the-best-way-to-sort-an-ilistt-in-net-20

    ReplyDelete
  11. Thanks. I'm glad it helped. Just a little payment for all the help I find each and every day on blogs out there. =) Keep coding!

    ReplyDelete
  12. Superb - took me two minutes to implement and job done!

    ReplyDelete
  13. Anonymous4:29 AM

    Thanks very much! Worked right away!

    ReplyDelete
  14. For most up-to-date news you have to go to see the web and on internet I found this web site as a finest site for hottest updates.

    ReplyDelete
  15. Its like you read my mind! You appear to know a lot approximately this, such as you wrote the e-book in it or something. I feel that you could do with a few percent to drive the message house a little bit, but other than that, this is great blog. A fantastic read. I'll certainly be back.

    ReplyDelete