Saturday, October 31, 2009

HashSet Collection

Introduction

I believe that many of us find ourselves writing a code that checks if object already exists in collection before we add it. The purpose of this check is creating a collection which holds unique objects, or simply a math set.

HashSet Collection

A HashSet is a collection that contains no duplicate elements, with no particular order. It was introduced in .NET framework 3.5 and provides high-performance set operations.

Since this object was modeled as mathematical set, it supports common set operations like Union and Intersection.

A HashSet has Add method which returns a boolean result indicating whether an element was added to collection or not (in case it already exists).

HashSet Using Example

HashSet<int> set1 = new HashSet<int>();
set1.Add(1);
set1.Add(2);
set1.Add(3);
set1.Add(1); //won't be added

HashSet<int> set2 = new HashSet<int>();
set2.Add(3);
set2.Add(5);
set2.Add(6);

//Produces an united set by using Union method.
HashSet<int> unionSet = new HashSet<int>(set1.Union(set2));
//UnionWith - modifies set1 itself.
set1.UnionWith(set2);

//Produces an intesected set by using Intersect method.
HashSet<int> interectSet = new HashSet<int>(set1.Intersect(set2));
//IntersectWith - modifies set1 itself.
set1.IntersectWith(set2);

You can see the complete HashSet documentation here.

Mark.

1 comment: