Ad space (banner)
๐Ÿ”ทVB.NET Lessons
Lesson 61 / 68

Set operations with HashSet (union, intersection, difference)

This lesson covers unions, intersections, and differences with VB.NET's HashSet, with the aim of understanding the basics of set operations.

UnionWith() gives the union (everything in either), IntersectWith() the intersection (what they share), and ExceptWith() the difference (what only one has). The mathematics maps straight onto the code.

The sample code applies each method to the two HashSets {1, 2, 3, 4} and {3, 4, 5, 6} and shows the union, intersection, and difference. Note that it copies first so as not to destroy the originals.

A common early stumble is that these methods change the set they are called on. To keep the original data you first make a copy with New HashSet(Of Integer)(a), as the sample does.

In professional work, set operations are applied constantly — finding the users common to two groups, listing what only one of two lists contains.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run VB.NET directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)