|
-
Jan 9th, 2009, 11:55 AM
#1
Thread Starter
PowerPoster
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>
Last edited by Techno; Jan 9th, 2009 at 12:28 PM.
-
Jan 10th, 2009, 01:55 PM
#2
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; });
-
Jan 10th, 2009, 05:13 PM
#3
Thread Starter
PowerPoster
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
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|