11.6. Using a HashSet Object

Problem

You need an object that contains a group of unique unordered objects. This object must be able to be compared to other objects containing unique unordered groups of similar objects. In addition, the two must be able to have the following actions performed on them:

  • Union of the items contained by the two container objects

  • Intersection of the items contained by the two container objects

  • Difference of the items contained by the two container objects

Solution

Use the built in HashSet<T> object.

The methods defined in Table 11-8 are of particular interest to using a HashSet<T> object.

Table 11-8. Members of the HashSet<T> class

Member

Description

Add method

Add a new object to the current HashSet<T> object. Its syntax is:

	Add(T obj)

where obj is the object of type T to add to this HashSet.

Removemethod

Removes an existing object from the current HashSet<T> object. Its syntax is:

	Remove(T obj)

where obj is the object of type T to remove from this HashSet.

RemoveWhere method

Removes an existing object from the current HashSet<T> object. Its syntax is:

	RemoveWhere(Predicate<T> match)

where match is the condition in which must be satisfied in order to remove an item or items from this HashSet.

Contains method

Returns a Boolean indicating whether the object passed in exists within this HashSet<T> object. If a true is returned, the object exists; otherwise, it does not. Its syntax is:

	Contains(T obj)

where obj is the object of type T to be searched for.

UnionWith method ...

Get C# 3.0 Cookbook, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.