Sorting a custom collection
How is it possible to sort a custom strongly typed collection by a specific field of an object?
so I have a collection which is of type "Article"
I now want to add article objects to this collection BUT when it adds the item, I want to sort the collection by a specific field on the article (in this case, for example the ID field of type integer)
any ideas?
I am implementing the IComparable and overriding the CompareTo but doesnt seem to fire it. Also... inheriting from Collection<T>
Re: Sorting a custom collection
Can you use a List<Article> (it does inherit from Collection)? You'll have a .Sort() method in there, to which you pass a delegate in which you perform your comparison.
Code:
ListName.Sort(delegate(Article a1, Article a2) { return a1.ID > a2.ID; });
Re: Sorting a custom collection
yeh exactly. funny thing, after 10 mins all i did was change from collection to list and it works fine...
unfortunately they arent using .NET 3.5 but im able to just call Sort() method on the collection which then invokes the overriden CompareTo method from the IComparable interface ;)