BLOG.CSHARPHELPER.COM: Use the HashSet class to represent sets and perform set operations in C#
Use the HashSet class to represent sets and perform set operations in C#
The HashSet class can represent objects in a set and perform set operations such as finding the union or intersection of two sets.
When the program starts, the following code builds two sets and performs some operations with them.
// Make some sets and perform operations on them. private void Form1_Load(object sender, EventArgs e) { HashSet owns_a_car = new HashSet(); HashSet owns_a_bike = new HashSet();
The code makes two sets named owns_a_car and owns_a_bike, and displays them.
The program makes a copy of owns_a_car, uses its IntersectWith method to find the intersection of the two sets, and displays the result (people who own both cars and bikes).
The program makes another copy of owns_a_car, uses its UnionWith method to find the intersection of the two sets, and displays the result (people who own either cars or bikes or both).
Finally the program makes a third copy of owns_a_car, uses its SymmetricExceptWith method to find items in one set or the other but not both (Xor), and displays the result (people who a bike or car but not both).
The HashSet class provides other set-related methods such as IsSubsetOf, IsPropertySubsetOf, IsSupersetOf, etc.
Comments