Login or Sign Up to become a member!
LessThanDot Sit Logo

LessThanDot

Desktop Developer

Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.

LTD Social Sitings

Lessthandot twitter Lessthandot Linkedin Lessthandot friendfeed Lessthandot facebook Lessthandot rss

Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.

Your profile

Search

XML Feeds

Google Ads

« Let Resharper do the heavy lifting for you.VB.Net: Using PostSharp and Log4PostSharp »
comments
Rate Post:
submit to reddit Digg!FacebookDotnetkicks

In Java, they have had a set implementation for ages. Well, .Net has it too. So no more need to import Iesi.set. The HashSet<T> or HashSet(Of T) is one of the collections you need most. For this to work, your objects need to override the Equals and GetHashCode functions, so that they reflect the business rules.

I have an example here of a List:

  1. Module Module1
  2.  
  3.     Sub Main()
  4.         Dim personlist As List(Of Person) = New List(Of Person)()
  5.         Dim person1 As Person = New Person("Chris", "Baes")
  6.         Dim person2 As Person = New Person("Chris", "Baes")
  7.         Console.WriteLine(person1.Equals(person2))
  8.         Dim person3 As Person = New Person("Chris1", "Baes")
  9.         Console.WriteLine(person3.Equals(person2))
  10.         personlist.Add(person1)
  11.         Console.WriteLine(personlist.Count)
  12.         personlist.Add(person2)
  13.         Console.WriteLine(personlist.Count)
  14.         personlist.Add(person3)
  15.         Console.WriteLine(personlist.Count)
  16.         Console.ReadLine()
  17.     End Sub
  18.  
  19.     Public Class Person
  20.         Implements IComparable
  21.  
  22.         Private _firstName As String
  23.         Private _lastName As String
  24.  
  25.         Public Sub New(ByVal FirstName As String, ByVal LastName As String)
  26.             _firstName = FirstName
  27.             _lastName = LastName
  28.         End Sub
  29.  
  30.         Public Property FirstName() As String
  31.             Get
  32.                 Return _firstName
  33.             End Get
  34.             Set(ByVal value As String)
  35.                 _firstName = value
  36.             End Set
  37.         End Property
  38.  
  39.         Public Property LastName() As String
  40.             Get
  41.                 Return _lastName
  42.             End Get
  43.             Set(ByVal value As String)
  44.                 _lastName = value
  45.             End Set
  46.         End Property
  47.  
  48.         Public Overrides Function Equals(ByVal obj As Object) As Boolean
  49.             Return obj.FirstName.Equals(Me.FirstName)
  50.         End Function
  51.  
  52.         Public Overrides Function GetHashCode() As Integer
  53.             Return Me.FirstName.GetHashCode()
  54.         End Function
  55.  
  56.         Public Function CompareTo(ByVal obj As Object) As Integer Implements System.IComparable.CompareTo
  57.             obj.FirstName.compareto(Me.FirstName)
  58.         End Function
  59.     End Class
  60. End Module

And the C# implementation:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace Testing_list_C
  7. {
  8.     class Program
  9.     {
  10.         static void Main(string[] args)
  11.         {
  12.             List<Person> personlist = new List<Person>();
  13.             Person person1 = new Person("Chris", "Baes");
  14.             Person person2 = new Person("Chris", "Baes");
  15.             Console.WriteLine(person1.Equals(person2));
  16.             Person person3 = new Person("Chris1", "Baes");
  17.             Console.WriteLine(person3.Equals(person2));
  18.             personlist.Add(person1);
  19.             Console.WriteLine(personlist.Count);
  20.             personlist.Add(person2);
  21.             Console.WriteLine(personlist.Count);
  22.             personlist.Add(person3);
  23.             Console.WriteLine(personlist.Count);
  24.             Console.ReadLine();
  25.         }
  26.     }
  27.  
  28.     class Person:IEquatable<Person>
  29.     {
  30.         String firstName;
  31.         String lastName;
  32.  
  33.         public Person(String FirstName, String LastName)
  34.         {
  35.             firstName = FirstName;
  36.             lastName = LastName;
  37.         }
  38.  
  39.         public String FirstName
  40.         {
  41.             get
  42.             {
  43.                 return firstName;
  44.             }
  45.             set
  46.             {
  47.                 firstName = value;
  48.             }
  49.         }
  50.  
  51.         public String LastName
  52.         {
  53.             get
  54.             {
  55.                 return lastName;
  56.             }
  57.             set
  58.             {
  59.                 lastName = value;
  60.             }
  61.         }
  62.  
  63.         public bool Equals(Person obj)
  64.         {
  65.             return obj.firstName.Equals(this.firstName);
  66.         }
  67.  
  68.         public bool Equals(Object obj)
  69.         {
  70.             return ((Person)obj).firstName.Equals(this.firstName);
  71.         }
  72.     }
  73. }

The Result will be:

True
False
1
2
3

If you replace the List with HashSet then the result will be:

True
False
1
1
2

The only problem is that you will not get any sort of exceptions. It will just not add it to the HashSet and go on with its business as usual. So I wouldn’t call this very user friendly because the user doesn’t understand, you have to explain, but I guess that is our job and it is easily solved with contains.

About the Author

User bio imageChristiaan is a forensic technician who programs on the side, although my function description says that I do IT-things for 90% of the time . I'm an avid VB.NET fan and I use lots of the ALT.Net techniques, like unit-testing, nhibernate, logging, IoC, ...
Social SitingsTwitterLinkedInHomePageLTD RSS Feed
759 views
submit to reddit Digg!FacebookDotnetkicks

Comments and Feedback

3 comments

Comment from: webbes [Member] Email
"The only problem is that you will not get any sort of exceptions. It will just not add it to the HashSet and go on with its business as usual. So I wouldn’t call this very user friendly because the user doesn’t understand, you have to explain, but I guess that is our job and it is easily solved with contains."

"Return Value
Type: System..::.Boolean

true if the element is added to the HashSet<(Of <(T>)>) object; false if the element is already present."

Cheers,
Wes
21/08/08 @ 03:54
Comment from: chrissie1 [Member] Email
YOu are absolutely right. I didn't even notice that.
Not sure if it will help much. Instead of this

If Not _sortedList.Contains(person1) then
_sortedList.Add(person1)
Else
MessageBox.Show("Don't do that")
End If

I could write this.

If Not _sortedList.Add(person1) Then
MessageBox.Show("Don't do that")
End IF

Or something similar ;-)
21/08/08 @ 04:19
Comment from: Alex Ullrich [Member] Email
Its also important to note the performance advantages of the hash set for Contains and Remove (IMO). For large lists it is MUCH faster.

Or let someone else do it:

http://blogs.msdn.com/bclteam/archive/2006/11/09/introducing-hashset-t-kim-hamilton.aspx
21/08/08 @ 06:56

Leave a comment


Your email address will not be revealed on this site.

Your URL will be displayed.
(Line breaks become <br />)
(Name, email & website)
(Allow users to contact you through a message form (your email will not be revealed.)