Perform set operations in C#

[set operations]

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 Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in algorithms, classes, mathematics and tagged , , , , , , , , , , , . Bookmark the permalink.

2 Responses to Perform set operations in C#

  1. Pingback: Use set operators in C# - C# HelperC# Helper

  2. Pingback: Use steganography to hide messages in an image in C#C# Helper

Leave a Reply

Your email address will not be published. Required fields are marked *