[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Perform set operations in C#

[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<string> owns_a_car = new HashSet<string>(); HashSet<string> owns_a_bike = new HashSet<string>(); owns_a_bike.Add("Alice"); owns_a_bike.Add("Bob"); owns_a_bike.Add("Fred"); owns_a_bike.Add("Dan"); owns_a_car.Add("Cindy"); owns_a_car.Add("Dan"); owns_a_car.Add("Emma"); owns_a_car.Add("Bob"); owns_a_car.Add("Fred"); txtOwnsABike.Text = string.Join(", ", owns_a_bike.ToArray()); txtOwnsACar.Text = string.Join(", ", owns_a_car.ToArray()); // Intersection. HashSet<string> owns_both = new HashSet<string>(owns_a_car); owns_both.IntersectWith(owns_a_bike); txtOwnsBoth.Text = string.Join(", ", owns_both.ToArray()); // Union. HashSet<string> owns_either = new HashSet<string>(owns_a_car); owns_either.UnionWith(owns_a_bike); txtOwnsEither.Text = string.Join(", ", owns_either.ToArray()); // Xor. HashSet<string> owns_one = new HashSet<string>(owns_a_car); owns_one.SymmetricExceptWith(owns_a_bike); txtOwnsOne.Text = string.Join(", ", owns_one.ToArray()); }

The code makes two sets named owns_a_car and owns_a_bike, and displays them.

The program then 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 union 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--I don't know why they didn't just name this method Xor), and displays the result (people who own a bike or car but not both).

The HashSet class provides other set-related methods such as IsSubsetOf, IsPropertySubsetOf, IsSupersetOf, and so forth.

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.