Results 1 to 3 of 3

Thread: Sorting a custom collection

  1. #1

    Thread Starter
    PowerPoster
    Join Date
    Aug 2003
    Location
    Edinburgh, UK
    Posts
    2,773

    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.

    MVP 2007-2010 any chance of a regain?
    Professional Software Developer and Infrastructure Engineer.

  2. #2
    I'm about to be a PowerPoster! mendhak's Avatar
    Join Date
    Feb 2002
    Location
    Ulaan Baator GooGoo: Frog
    Posts
    38,170

    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; });

  3. #3

    Thread Starter
    PowerPoster
    Join Date
    Aug 2003
    Location
    Edinburgh, UK
    Posts
    2,773

    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

    MVP 2007-2010 any chance of a regain?
    Professional Software Developer and Infrastructure Engineer.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width