Results 1 to 3 of 3

Thread: compareTo/Equals

  1. #1

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

    compareTo/Equals

    It's been a while since ive done this. Basically I have an object with properties which include:

    ID (int)
    name (string)


    I want to be able to sort the collection based on the name. I have implemented and overriden CompareTo, Equals, GetHashCode and ToString however I have noticed that it shows me much less items in the collection than before overriding these. Any ideas where I am going wrong?


    public int CompareTo(GenericListRecip other)
    {
    return this.name.CompareTo(other.name); //this method does not even get called!
    }

    public override string ToString()
    {
    return this.name;
    }

    public override int GetHashCode()
    {
    return this.id;
    }

    public override Equals(object obj)
    {
    if (obj is GenericListRecip)
    {
    return this.name == ((GenericListRecip)obj).name;
    }
    else
    {
    return false;
    }
    }




    obviously if i take the implementation out - its all fine but doesnt sort it by the property/field I would like. Any ideas?

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

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: compareTo/Equals

    If you want to be able to sort a list of these objects then you should implement the IComparable interface. It is IComparable.Compare that is used when sorting.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3

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

    Re: compareTo/Equals

    Thanks, I did implement that but that didn't quite work however ive managed to make it work now - I had to call the Sort() method excplicitly...seems to work fine, calls the compareto method and works fine :-/

    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