Collection Types - Sets

The .NET 3.5 Framework introduced yet another useful collection class, known as HashSet, which is defined in the System.Collections.Generic namespace. HashSet implements the typical set operations that you would expect. For example, you can call the IntersectWith method to modify the current set so that it will contain an intersection of the current items and the items contained in the IEnumerable<T> type given. Conversely, UnionWith modifies the current set to contain the union of two sets. Other useful methods include IsSubsetOf, IsSupersetOf, ExceptWith, SymmetricExceptWith, Contains, etc. These are just a few of the useful methods available for sets.

As is typical with set operations, you can only add unique values to instances of HashSet. For example, if you have already added the values 1, 2, and 3 to a HashSet<int> instance, then you cannot add another integer corresponding to one of those values. This is the reason the Add method returns a Boolean indicating whether the operation succeeded or not. It would be inefficient to throw an exception in such cases, so the result is indicated via the return value from Add.

Notice that the various set operation methods implemented by HashSet accept parameters of type IEnumerable<T>. This is very handy because it allows you to use any collection type as the parameter to these methods rather than only HashSet instances.

Source Of Information : Apress Accelerated C Sharp 2010

0 comments


Subscribe to Developer Techno ?
Enter your email address:

Delivered by FeedBurner