Adsense

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:

Bhramara said...

Good One! Helped us a lot. Thanks.

Anonymous said...

Thanks, I needed that.

Anonymous said...

Thanks! Helped me too...
Regards

Anonymous said...

Thanks! Quick and easy!

Anonymous said...

Thanks
helped me too

Max said...
This comment has been removed by the author.
Anonymous said...

Great post!

Anonymous said...

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

Anonymous said...

Cool. Exactly what I was looking for. Thanks!

Anonymous said...

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

Paul Fox said...

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!

Unknown said...

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

Anonymous said...

Thanks very much! Worked right away!

ed treatment tablets said...

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.

herbal erection pills said...

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.