Working with ICollection/List/IEnumerable that contain custom classes

Leave a comment

Again, about my Twitter Client. I’ve made a custom class show the tweet and then a ICollection for the public property of the Tweets in the TwitterViewModel.

Problem: Each I time I get new tweets I have to empty the Collection. I tried to use the Contains method every time I added a new Tweet, but as Pete Brown said that will always return false.

Solution: Implement IEquatable on my Tweet class. Now when Contains check if the tweet exists in the list it will work.

Other example.

Say you have this custom class:

class User
{
      public string Name { get; set; }
      public long ID { get; set; }
}

Not going to bother INotifyPropertyChanged. This will be only about the IEquatable class.

Create a ICollection and add some data:

ICollection list = new List();
list.Add(new User { Name = “Robert”, ID = 123409 });
list.Add(new User { Name = “Pete”, ID = 23410 });

Now. Say you have some form that creates a new User, check if it exists and then tries to add it. For sake of simplicity I won’t use a form:

var user = new User { Name = “Pete”, ID= 23410 });
if(!list.Contains(user))
     list.Add(user);

This won’t work. It’ll add it even you know that it contains it. Simply put “Two instances of a class representing the same tweet (or in this case user) are two different things.” (@Pete_Brown on Twitter)

Implement the IEquatable class and your class should look like this:

class User: IEquatable
{
      public string Name { get; set; }
      public long ID { get; set; }

      public bool Equals(User other)
      {
            if(other.ID == this.ID)
                  return true;
            else
                  return false;
      }
}

Now Contains() will work properly and your List manipulations will work like a charm.

Hope you found this post useful. It’s been a pain of figuring it out. Had help from Pete Brown.
Subscribe to his blog: http://10rem.net
Follow him on Twitter: http://twitter.com/Pete_Brown

Me? You can find my blog at https://robertiagar.wordpress.com/ (mouthful I know) and Twitter: http://twitter.com/RobertIagar

Stay tuned for more interesting finds…

Advertisements

Working with ICollection/List/IEnumerable that contain custom classes

3 Comments

Again, about my Twitter Client. I’ve made a custom class show the tweet and then a ICollection for the public property of the Tweets in the TwitterViewModel.

More