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:
Good One! Helped us a lot. Thanks.
Thanks, I needed that.
Thanks! Helped me too...
Regards
Thanks! Quick and easy!
Thanks
helped me too
Great post!
Thanks a lot ! It's exactly what I'm lookin' for :)
Cool. Exactly what I was looking for. Thanks!
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
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!
Superb - took me two minutes to implement and job done!
Thanks very much! Worked right away!
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.
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.
Post a Comment