Home

A Set as a Collection of Elements

   

Fundamentals of a Set

 

Introduction

A set is a list of items with various goals:

  • To know whether the set is empty or it contains at least one item
  • To find out whether a set (already) contains a certain value
  • To compare one set to another. Some of the sought results are to find out if two sets are the same, if one set is less than the other, etc

To support sets, the .NET Framework provides a class named HashSet. This class is created in the System.Collections.Generic namespace.

In algebra, a set is usually represented with an uppercase letter, such as A. In programming, we will represent the list with a name.

Consider the following list and notice that it contains an item twice:

using System;
using System.Windows.Forms;
using System.Collections.Generic;

// Use references to
// System
// System.Drawing
// System.Windows.Forms

public class SetHasher : Form
{
    ListBox lbxNames;

    public SetHasher()
    {
        InitializeComponent();
    }

    private void InitializeComponent()
    {
        lbxNames = new ListBox();
        lbxNames.Location = new System.Drawing.Point(12, 12);
        lbxNames.Size = new System.Drawing.Size(120, 95);
        StartPosition = FormStartPosition.CenterScreen;

        Text = "Set Hasher";
        MinimizeBox = false;
        MaximizeBox = false;
        ClientSize = new System.Drawing.Size(145, 120);
        Load += new EventHandler(FormLoaded);
        Controls.Add(lbxNames);
    }

    private void FormLoaded(object sender, EventArgs ea)
    {
        List<string> names = new List<string>();

        names.Add("Kevin");
        names.Add("Jane");
        names.Add("Daniel");
        names.Add("Ruth");
        names.Add("Jane");
        names.Add("Paul");

        lbxNames.DataSource = names;
    }
}

public class Exercise
{
    [STAThread]
    public static int Main()
    {
        Application.Run(new SetHasher());
        return 0;
    }
}

Collection

In a .NET application, a set is a list that does not allow duplicate items.

Most of the time, in algebra, to study sets, we use numbers. In all of the examples in this lesson, we will use strings to make them more interesting. Obviously, integers would be easier. If you want to use numbers, all you have to do is to replace all strings in our examples with numbers.

 

ApplicationTopic Applied: Introducing Sets

  1. Start Microsoft Visual Studio or Microsoft Visual C# Express
  2. Create a Windows Application named Algebra2
  3. In the Solution Explorer, right-click Form1.cs and click Rename
  4. Type Algebra.cs and press Enter
  5. Click the body of the form to select it
  6. In the Properties window, change the following characteristics
    FormBorderStyle: FixedDialog
    Text: Operations on Sets
    StartPosition: CenterScreen
    MaximizeBox: False
    MinimizeBox: False
  7. Design the form as follows: 
     
    Sets
     
    Control Text Name
    Label Label Number:  
    TextBox Text Box   txtNumberA
    Button Button Add btnAddA
    ListBox List Box   lbxA

Creating an Empty Set

In algebra, a set is empty if it contains no element. This is the case for a brand new set. It can also happen if the elements in the set have been deleted. In algebra, to create an empty set, use an uppercase letter and assign the phi character to it. Here is an example:

A = ∅

(In algebra, an empty set is also called a null set.) In algebra, to visually represent a set, we draw a circle. If the set is empty, the circle is blank:

Set

To programmatically create an empty set, declare a variable of type HashSet and use the new operator to initialize it.

Depending on the type of set, one set can be made of natural numbers, another made of floating-point numbers, yet another one made of strings or other types of values (dates, times, etc). When programmatically creating a set, pass the type of items in the angle brackets. Here is an example:

private void FormLoaded(object sender, EventArgs ea)
{
    HashSet<string> names = new HashSet<string>();
}

The HashSet class is defined as follows:

[SerializableAttribute]
[HostProtectionAttribute(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
public class HashSet<T> : ICollection<T>, IEnumerable<T>, 
    IEnumerable, ISerializable, IDeserializationCallback

ApplicationTopic Applied: Creating an Empty Set

  1. Double-click an unoccupied of the form to generate its Load event
  2. Change the file as follows:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    
    namespace Algebra2
    {
        public partial class Algebra : Form
        {
            HashSet<int> A;
    
            public Algebra()
            {
                InitializeComponent();
            }
    
            private void Algebra_Load(object sender, EventArgs e)
            {
                A = new HashSet<int>();
            }
        }
    }
  3. Return to the form

Fundamental Operations on a Set

 

Populating a Set

Unless a set is empty, it must have or contain something. An object included in a set is called an element or a member of the set. In algebra, to create a set, we specify an uppercase letter, followed by = { }. In the curly brackets, we list the elements separated by commas. Here is an example:

A = { Kevin, Jane, Daniel, Ruth, Paul }

To visually illustrate, you can represent each element in the circle. Here is an example:

Set

In programming, to create a set, after declaring a HashSet variable, we can call its Add() method whose syntax is:

public bool Add(T item);

Here are examples of calling this method:

private void FormLoaded(object sender, EventArgs ea)
{
    HashSet<string> names = new HashSet<string>();

    names.Add("Kevin");
    names.Add("Jane");
    names.Add("Daniel");
    names.Add("Ruth");
    names.Add("Paul");

    foreach (string str in names)
        lbxNames.Items.Add(str);
}

Collection

Notice that each element in this case is a constant, or has a constant value.

Remember that one of the rules of a set is that it cannot have duplicate items. If you add an item that exists in the list already, that item would not be added. In fact, to let you know whether an item was added, the HashSet<>.Add() method returns a Boolean value:

  • If the item is successfully added, the method returns true
  • If the addition is denied, the method returns false and the compiler does not throw an exception

The following code will illustrate:

private void FormLoaded(object sender, EventArgs ea)
{
    HashSet<string> names = new HashSet<string>();

    if (names.Add("Kevin") == true)
        MessageBox.Show("Kevin has been added to the list.",
                        "Hash Set Operations",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    else
        MessageBox.Show("Kevin was not added to the list.",
                        "Hash Set Operations",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    if (names.Add("Jane") == true)
        MessageBox.Show("Jane has been added to the list.",
                        "Hash Set Operations",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    else
        MessageBox.Show("Jane was not added to the list.",
                        "Hash Set Operations",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    if (names.Add("Daniel") == true)
        MessageBox.Show("Daniel has been added to the list.",
                        "Hash Set Operations",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    else
        MessageBox.Show("Daniel was not added to the list");
    if (names.Add("Ruth") == true)
        MessageBox.Show("Ruth has been added to the list.",
                        "Hash Set Operations",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    else
        MessageBox.Show("Ruth was not added to the list.",
                        "Hash Set Operations",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    if (names.Add("Jane") == true)
        MessageBox.Show("Jane has been added to the list.",
                        "Hash Set Operations",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    else
        MessageBox.Show("Jane was not added to the list.",
                        "Hash Set Operations",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    if (names.Add("Paul") == true)
        MessageBox.Show("Paul has been added to the list.",
                        "Hash Set Operations",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    else
        MessageBox.Show("Paul was not added to the list.",
                        "Hash Set Operations",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);

    foreach (string str in names)
        lbxNames.Items.Add(str);
}
Hash Set Hash Set
Hash Set Hash Set
Hash Set Hash Set
 

ApplicationTopic Applied: Populating a Set

  1. On the form, double-click the Add button
  2. Implement its event as follows:
    private void btnAddNumbers_Click(object sender, EventArgs e)
    {
        int x = 0;
    
        try
        {
            x = int.Parse(txtNumber.Text);
            A.Add(x);
        }
        catch (FormatException)
        {
            MessageBox.Show("The value you typed is not a valid number.",
                            "Algebra of Sets",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    
        lbxNumbers.Items.Clear();
    
        foreach (int element in A)
            lbxNumbers.Items.Add(element);
    
        txtNumber.Text = "";
        txtNumber.Focus();
    }
  3. Press Ctrl + F5 to execute
  4. Type a number in the text box and click Add
  5. Do that a few times
     
    Sets
  6. Close the form and return to your programming environment

The Number of Items in a Set

In algebra, when it comes to the number of elements in a set, there are two categories. A set is referred to as finite it contains a constant number of items. An example is the number of students in a classroom. A set is infinite if its number of items cannot be counted. An example is the number of stars in the sky.

The HashSet class implements the ICollection<> generic interface, which gives it a property named Count. This property allows you to know the number of elements in a set. Here is an example:

using System;
using System.Windows.Forms;
using System.Collections.Generic;

public class SetHasher : Form
{
    Label lblCount;
    ListBox lbxNames;

    public SetHasher()
    {
        InitializeComponent();
    }

    private void InitializeComponent()
    {
        lbxNames = new ListBox();
        lbxNames.Location = new System.Drawing.Point(12, 12);
        lbxNames.Size = new System.Drawing.Size(120, 95);

        lblCount = new Label();
        lblCount.AutoSize = true;
        lblCount.Location = new System.Drawing.Point(12, 115);

        Text = "Set Hasher";
        MinimizeBox = false;
        MaximizeBox = false;
        StartPosition = FormStartPosition.CenterScreen;
        ClientSize = new System.Drawing.Size(145, 140);
        Load += new EventHandler(FormLoaded);

        Controls.Add(lbxNames);
        Controls.Add(lblCount);
    }

    private void FormLoaded(object sender, EventArgs ea)
    {
        HashSet<string> names = new HashSet<string>();

        names.Add("Kevin Walchild");
        names.Add("Jane Overton");
        names.Add("Daniel Albertson");
        names.Add("Ruth Oyawale");
        names.Add("Jane Ouelette");
        names.Add("Paul Sullivan");

        foreach (string str in names)
            lbxNames.Items.Add(str);

        lblCount.Text = "The list contains " + names.Count.ToString() + " items";
    }
}

public class Exercise
{
    [STAThread]
    public static int Main()
    {
        Application.Run(new SetHasher());
        return 0;
    }
}

Collection

Checking Whether a Set Contains a Certain Element

In algebra, to represent that a certain value "a" exists in a set A, we would write:

a ∈ A

This is read as "a is an element of set A" or "a is included in set A" or "Set A contains a". To support this operation, the HashSet class inherits the Contains() method from the ICollection<> interface. The method allows you to check whether the list already contains a certain item. Here are examples of calling this method:

private void FormLoaded(object sender, EventArgs ea)
{
    HashSet<string> names = new HashSet<string>();

    names.Add("Kevin Walchild");
    names.Add("Jane Overton");
    names.Add("Daniel Albertson");
    names.Add("Ruth Oyawale");
    names.Add("Jane Ouelette");
    names.Add("Paul Sullivan");

    foreach (string str in names)
        lbxNames.Items.Add(str);

    if( names.Contains("Jane Owerton") )
        MessageBox.Show("The list contains Jane Owerton.",
                        "Hash Set Operations",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    else
        MessageBox.Show("The list doesn't contain Jane Owerton",
                        "Hash Set Operations",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);

    if( names.Contains("Jane Overton") )
        MessageBox.Show("The list contains Jane Overton.",
                        "Hash Set Operations",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    else
        MessageBox.Show("The list doesn't contain Jane Overton",
                        "Hash Set Operations",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);

    lblCount.Text = "The list contains " + names.Count.ToString() + " items";
}
Hash Set Hash Set

In algebra, to state that an element a is not in the set A, we write:

a ∉ A

This reads "a is not an element of set A" or "a is not included in set A" or "Set A does not contain a". To perform this checking in programming, you can use the NOT operator "!".

Creating a Duplicate Set

In algebra, after creating a set A, you may want to create another set B but that contains the same elements as A. To do this, you can simply assign the elements of A to B. This would be done as follows:

A = { Kevin Walchild, Jane Overton, Daniel Albertson,
      Ruth Oyawale, Jane Ouelette, Paul Sullivan }

B = A

Now, sets A and B have the same elements:

Set

To support this operation, the HashSet class provides another constructor (in C++ and Pascal, we could use a copy constructor) whose syntax is:

public HashSet(IEnumerable<T> collection);

This constructor allows you to create a new set that is made of values from an existing set. You create the new list by passing the name of the existing list to this constructor. Here is an example:

 private void FormLoaded(object sender, EventArgs ea)
{
        HashSet<string> names = new HashSet<string>();

        names.Add("Kevin Walchild");
        names.Add("Jane Overton");
        names.Add("Daniel Albertson");
        names.Add("Ruth Oyawale");
        names.Add("Jane Ouelette");
        names.Add("Paul Sullivan");

        HashSet<string> people = new HashSet<string>(names);
}

Once you have created the list, you can manipulate it as you see fit. For example, you can add new items to it. Here is an example:

using System;
using System.Windows.Forms;
using System.Collections.Generic;

public class SetHasher : Form
{
    Label lblCount;
    Label lblPeople;
    ListBox lbxNames;
    ListBox lbxPeople;

    public SetHasher()
    {
        InitializeComponent();
    }

    private void InitializeComponent()
    {
        lbxNames = new ListBox();
        lbxNames.Location = new System.Drawing.Point(12, 12);
        lbxNames.Size = new System.Drawing.Size(120, 120);

        lbxPeople = new ListBox();
        lbxPeople.Location = new System.Drawing.Point(138, 12);
        lbxPeople.Size = new System.Drawing.Size(120, 120);
        
        lblCount = new Label();
        lblCount.AutoSize = true;
        lblCount.Location = new System.Drawing.Point(12, 126);

        lblPeople = new Label();
        lblPeople.AutoSize = true;
        lblPeople.Location = new System.Drawing.Point(138, 126);

        Text = "Set Hasher";
        MinimizeBox = false;
        MaximizeBox = false;
        StartPosition = FormStartPosition.CenterScreen;
        ClientSize = new System.Drawing.Size(270, 150);
        Load += new EventHandler(FormLoaded);

        Controls.Add(lbxNames);
        Controls.Add(lbxPeople);
        Controls.Add(lblCount);
        Controls.Add(lblPeople);
    }

    private void FormLoaded(object sender, EventArgs ea)
    {
        HashSet<string> names = new HashSet<string>();

        names.Add("Kevin Walchild");
        names.Add("Jane Overton");
        names.Add("Daniel Albertson");
        names.Add("Ruth Oyawale");
        names.Add("Jane Ouelette");
        names.Add("Paul Sullivan");

        foreach (string str in names)
            lbxNames.Items.Add(str);

        lblCount.Text = "Number of items: " + names.Count.ToString();

        HashSet<string> people = new HashSet<string>(names);
        people.Add("Antoinette Belton");
        people.Add("Joshua Melmann");

        foreach (string str in people)
            lbxPeople.Items.Add(str);

        lblPeople.Text = "Number of items: " + people.Count.ToString();
    }
}

public class Exercise
{
    [STAThread]
    public static int Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new SetHasher());
        return 0;
    }
}

Collection

ApplicationTopic Applied: Duplicating a Set

  1. Change the design of the form as follows: 
     
    Sets
     
    Control Text Name
    Label Label Number:  
    TextBox Text Box   txtNumberA
    Button Button Add btnAddNumberA
    ListBox ListBox   lbxNumbersA
    Button Button Duplicate btnDuplicate
    ListBox List Box   lbxNumbersB
  2. Double-click the Duplicate button
  3. Change the file as follows:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    
    namespace Algebra2
    {
        public partial class Algebra : Form
        {
            HashSet<int> A;
            HashSet<int> B;
    
            public Algebra()
            {
                InitializeComponent();
            }
    
            private void Algebra_Load(object sender, EventArgs e)
            {
                A = new HashSet<int>();
                B = new HashSet<int>();
            }
    
            private void btnAddNumberA_Click(object sender, EventArgs e)
            {
                int x = 0;
    
                try
                {
                    x = int.Parse(txtNumberA.Text);
                    A.Add(x);
                }
                catch (FormatException)
                {
                    MessageBox.Show("The value you typed is not a valid number.",
                                    "Algebra of Sets",
                                 MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
    
                lbxNumbersA.Items.Clear();
    
                foreach (int element in A)
                    lbxNumbersA.Items.Add(element);
    
                txtNumberA.Text = "";
                txtNumberA.Focus();
            }
    
            private void btnDuplicate_Click(object sender, EventArgs e)
            {
                B = A;
    
                foreach (int element in B)
                    lbxNumbersB.Items.Add(element);
            }
        }
    }
  4. To execute, press Ctrl + F5
  5. Add a few numbers to the left list box. Here is an example:
     
    Sets
  6. Click Duplicate
     
    Sets
  7. Close the form and return to your programming environment

Operations on Sets

   

Comparing For Equality

Imagine you have two sets A and B defined as follows:

A = { Kevin Walchild, Jane Overton, Daniel Albertson, Jane Ouelette }
B = { Daniel Albertson, Kevin Walchild, Jane Ouelette, Jane Overton }

Notice that both sets have the same elements. When two sets have exact same members, we say that those sets are equal. This can be expressed as:

A = B

This operation is commutative, which means the above operation can also be written as:

B = A

We already know that all classes used in a C# application (or a .NET project) derive from the Object class and they inherit a method named Equals. This makes it possible to compare two values or two objects for equality. The HashSet class also naturally inherits this method. Although you can use that method, the HashSet class provides its own custom method named SetEquals. Its syntax is:

public bool SetEquals(IEnumerable<T> other);

This method takes as argument another HashSet list and compares both sets. If the sets are the same, the method returns true. Otherwise it produces a false value. Here are examples of calling this method:

private void FormLoaded(object sender, EventArgs ea)
{
    HashSet<string> names = new HashSet<string>();

    names.Add("Kevin Walchild");
    names.Add("Jane Overton");
    names.Add("Daniel Albertson");
    names.Add("Ruth Oyawale");
    names.Add("Jane Ouelette");
    names.Add("Paul Sullivan");

    foreach (string str in names)
        lbxNames.Items.Add(str);

    lblCount.Text = "Number of items: " + names.Count.ToString();

    HashSet<string> people = new HashSet<string>(names);

    if (people.SetEquals(names) == true)
        MessageBox.Show("Both collections are the same.",
                        "Collection Class",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    else
        MessageBox.Show("These collections are different.",
                        "Collection Class",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);

    people.Add("Antoinette Belton");
    people.Add("Joshua Melmann");

    if (people.SetEquals(names) == true)
        MessageBox.Show("Both collections are the same.",
                        "Collection Class",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    else
        MessageBox.Show("These collections are different.",
                        "Collection Class",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);

    foreach (string str in people)
        lbxPeople.Items.Add(str);

    lblPeople.Text = "Number of items: " + people.Count.ToString();
}
Hash Set Hash Set
  

ApplicationTopic Applied: Comparing For Equality

  1. Add a button between the list boxes as follows: 
     
    Sets
     
    Control Text Name
    Button Button Compare btnCompare
  2. Double-click the Compare button
  3. Implement the event as follows:
    private void btnCompare_Click(object sender, EventArgs e)
    {
        if (A.SetEquals(B))
            MessageBox.Show("A is equal to B",
                            "Algebra of Sets",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        else
            MessageBox.Show("A is different from B",
                        "Algebra of Sets",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
  4. Return to the form
  5. To execute, press Ctrl + F5
  6. Add a few numbers to the left list box. Here is an example:
     
    Sets
  7. Click Compare
     
    Sets
  8. Click OK
  9. Click Duplicate
  10. Click Compare
     
    Sets
  11. Click OK
  12. Close the form and return to your programming environment

A Subset of Another Set

Imagine you have two sets A and B defined as follows:

A = { Kevin, Jane, Daniel }
B = { Raul, Kevin, Tiffany, Daniel, Michael, Jane, Paul }

Notice that all members of A are also members of B. In algebra, to express this, we write:

A ⊂ B

This is the same as:

 { Kevin, Jane, Daniel } ⊂ { Raul, Kevin, Tiffany, Daniel, Michael, Jane, Paul }

We say that A is a subset of B. This can be visually illustrated as follows:

A Sub-Set of an Existing Set

In algebra, any set is a subset of itself. Also, since the empty set doesn't have any element, the empty set is a subset of any set. We write it as:

∅ ⊂ A

and

∅ ⊂ B

An empty set is also a subset of itself.

To let you find out you whether one set is a subset of another, the HashSet class provides the IsSubsetOf() method. Its syntax is:

public bool IsSubsetOf(IEnumerable<T> other);

If the set passed as argument is a subset of the variable that called the method, it returns true. Otherwise, it returns false. Here is an example of calling this method:

private void FormLoaded(object sender, EventArgs ea)
{
    HashSet<string> Persons = new HashSet<string>();

    Persons.Add("Kevin Walchild");
    Persons.Add("Jane Overton");
    Persons.Add("Daniel Albertson");

    HashSet<string> People = new HashSet<string>();
    People.Add("Raul Fitzgerald");
    People.Add("Kevin Walchild");
    People.Add("Tiffany Morales");
    People.Add("Daniel Albertson");
    People.Add("Michael Rhodia");
    People.Add("Ruth Oyawale");
    People.Add("Jane Overton");
    People.Add("Paul Sullivan");

    if (Persons.IsSubsetOf(People))
        MessageBox.Show("The Persons set is a subset of the People set.",
                        "Collection Class",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    else
        MessageBox.Show("The Persons set is not a subset of the People set.",
                        "Collection Class",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);

    foreach (string str in Persons)
        lbxNames.Items.Add(str);

    lblCount.Text = "Number of items: " + Persons.Count.ToString();

    foreach (string str in People)
        lbxPeople.Items.Add(str);

    lblPeople.Text = "Number of items: " + People.Count.ToString();
}

Hash Set

It is important to know that the subset relationship is one way; in other words, the comparison is not commutative: the fact that a set A is a subset of a set B is not vice-versa.

ApplicationTopic Applied: Checking for Sub-Set

  1. Add another label to the form and change its Text to Number
  2. Add a second text box and another button to the form
  3. Change the design of the form as follows: 
     
    Sets
     
    Control Text Name
    Label Label Number:  
    TextBox Text Box   txtNumberA
    Button Button Add btnAddNumberA
    Label Label Number:  
    TextBox Text Box   txtNumberB
    Button Button Add btnAddNumberB
  4. On the form, double-click the second Add button
  5. Implement its event as follows:
    private void btnAddNumberB_Click(object sender, EventArgs e)
    {
        int x = 0;
    
        try
        {
            x = int.Parse(txtNumberB.Text);
            B.Add(x);
        }
        catch (FormatException)
        {
            MessageBox.Show("The value you typed is not a valid number.",
                            "Algebra of Sets",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    
        lbxNumbersB.Items.Clear();
    
        foreach (int element in B)
            lbxNumbersB.Items.Add(element);
    
        txtNumberB.Text = "";
        txtNumberB.Focus();
    }
  6. Change the code of the Compare button as follows:
    private void btnCompare_Click(object sender, EventArgs e)
    {
        if (A.SetEquals(B))
            MessageBox.Show("A is equal to B.",
                            "Algebra of Sets",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        else
            MessageBox.Show("A is different from B.",
                        "Algebra of Sets",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    
        if( A.IsSubsetOf(B))
            MessageBox.Show("A is a sub-set of B.",
                            "Algebra of Sets",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        else
            MessageBox.Show("A is not a sub-set of B.",
                        "Algebra of Sets",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
  7. To execute, press Ctrl + F5
  8. Add a few numbers to the left list box
  9. Add the same numbers to the right list box in any order of your choice
  10. Add a few more numbers to the right list. Here is an example:
     
    Sets
  11. Click Compare
     
    Sets
  12. Click OK
  13. Close the form and return to your programming environment

A Proper Subset of Another Set

A set is a subset of itself. Also, when two sets have the exact same members, each set is a subset of the other:

Set

On the other hand, if you have a set A that is strictly a subset of another set B, this means there is at least one element in set B that is not a member of set A. In this case, we say that set A is a property subset of set B. This can be illustrated as follows:

Set

To let you find out if a set is a proper subset of another set, the HashSet class is equipped with the IsProperSubsetOf() method. Its syntax is:

public bool IsProperSubsetOf(IEnumerable<T> other);

This method takes a HashSet value as arguments and performs a comparison on their elements:

  • If both sets are the same, the method returns false
  • If the argument has at least one element that is not in the variable that called it, the method returns false
  • If all elements of the argument's set are members of the variable that called it, the method returns true

Here are two examples of calling this method:

private void FormLoaded(object sender, EventArgs ea)
{
    HashSet<string> Persons = new HashSet<string>();
    Persons.Add("Kevin Walchild");
    Persons.Add("Frank Maguire");
    Persons.Add("Jane Overton");
    Persons.Add("Daniel Albertson");

    HashSet<string> Students = new HashSet<string>();
    Students.Add("Jane Overton");
    Students.Add("Kevin Walchild");
    Students.Add("Daniel Albertson");
    Students.Add("Frank Maguire");

    HashSet<string> People = new HashSet<string>();
    People.Add("Raul Fitzgerald");
    People.Add("Kevin Walchild");
    People.Add("Tiffany Morales");
    People.Add("Daniel Albertson");
    People.Add("Michael Rhodia");
    People.Add("Frank Maguire");
    People.Add("Ruth Oyawale");
    People.Add("Jane Overton");
    People.Add("Paul Sullivan");

    if (Persons.IsProperSubsetOf(Students))
        MessageBox.Show("The Persons set is a proper subset of the Students set.",
                        "Collection Class",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    else
       MessageBox.Show("The Persons set is not a proper subset of the Students set.",
                        "Collection Class",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);

    if (Persons.IsProperSubsetOf(People))
        MessageBox.Show("The Persons set is a proper subset of the People set.",
                        "Collection Class",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    else
        MessageBox.Show("The Persons set is not a proper subset of the People set.",
                        "Collection Class",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
}

Hash Set

Hash Set

ApplicationTopic Applied: Checking for Proper Sub-Set

  1. Change the code of the Compare button as follows:
    private void btnCompare_Click(object sender, EventArgs e)
    {
        if (A.SetEquals(B))
            MessageBox.Show("A is equal to B.",
                            "Algebra of Sets",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        else
            MessageBox.Show("A is different from B.",
                        	"Algebra of Sets",
                        	MessageBoxButtons.OK, MessageBoxIcon.Information);
    
        if( A.IsSubsetOf(B))
            MessageBox.Show("A is a sub-set of B.",
                            "Algebra of Sets",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        else
            MessageBox.Show("A is not a sub-set of B.",
                        	"Algebra of Sets",
                        	MessageBoxButtons.OK, MessageBoxIcon.Information);
    
        if( A.IsProperSubsetOf(B))
            MessageBox.Show("A is a proper sub-set of B.",
                            "Algebra of Sets",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        else
            MessageBox.Show("A is not a proper sub-set of B.",
                            "Algebra of Sets",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
  2. To execute, press Ctrl + F5
  3. Add a few numbers to the left list box
  4. Add the same numbers for the right list box in any order of your choice
     
    Sets
  5. Click Compare
     
    Sets
  6. Click OK
  7. Add a few more numbers to the right list
  8. Click Compare. Here is an example:
     
    Sets
  9. Click OK
  10. Close the form and return to your programming environment
 
 
 

A Super-Set of an Existing Set

Remember that a sub-set is a set whose all elements are also found in another set. A super-set is the reverse of a sub-set. That is, in a superset, all the elements of a set B are found in a set A but set A may have elements that are not found in B. In algebra, this can be written as follows:

B ⊃ A

To help you make this comparison, the HashSet class is equipped with a method named IsSupersetOf. Its syntax is:

public bool IsSupersetOf(IEnumerable<T> other);

This method takes a HashSet object as argument and compares its elements to those of the variable that called it. If all the elements of the argument are found in the variable that called it, the method returns true.

ApplicationTopic Applied: Checking for Super-Set

  1. Change the code of the Compare button as follows:
    private void btnCompare_Click(object sender, EventArgs e)
    {
        if (A.SetEquals(B))
            MessageBox.Show("A is equal to B.",
                            "Algebra of Sets",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        else
            MessageBox.Show("A is different from B.",
                        "Algebra of Sets",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    
        if (A.IsSubsetOf(B))
            MessageBox.Show("A is a sub-set of B.",
                            "Algebra of Sets",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        else
            MessageBox.Show("A is not a sub-set of B.",
                        "Algebra of Sets",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    
        if (A.IsSupersetOf(B))
            MessageBox.Show("A is a super-set of B.",
                            "Algebra of Sets",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        else
            MessageBox.Show("A is not a super-set of B.",
                        "Algebra of Sets",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    
        if( A.IsProperSubsetOf(B))
            MessageBox.Show("A is a proper sub-set of B.",
                            "Algebra of Sets",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        else
            MessageBox.Show("A is not a proper sub-set of B.",
                        "Algebra of Sets",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
  2. To execute, press Ctrl + F5
  3. Add a few numbers to the left list box
  4. Add the same numbers to the right list box
  5. Add a few more numbers to the right list
  6. Click Compare
     
    Sets
  7. Click OK
  8. Close the form and return to your programming environment
  9. To execute again, press Ctrl + F5
  10. Add a few numbers to the left list box
  11. Add some, but not all, of same left numbers to the right list box
  12. Click Compare
     
    Sets
  13. Click OK
  14. Close the form and return to your programming environment

A Proper Super-Set of an Existing Set

When it comes to a super-set, if both sets are the same, each is considered a super-set of the other and the IsSupersetOf() method returns true. By contrast, if a set B is a super-set of A but both sets are not the same, that is, set B has more elements than set A, set B is said to be a property super-set of A. To let you make the comparison to determine this, the HashSet class provides a method named IsProperSupersetOf. Its syntax is:

public bool IsProperSupersetOf(IEnumerable<T> other);

ApplicationTopic Applied: Checking for a Proper Super-Set

  1. Change the code of the Compare button as follows:
    private void btnCompare_Click(object sender, EventArgs e)
    {
        if (A.SetEquals(B))
            MessageBox.Show("A is equal to B.",
                            "Algebra of Sets",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        else
            MessageBox.Show("A is different from B.",
                        "Algebra of Sets",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    
        if( A.IsSubsetOf(B))
            MessageBox.Show("A is a sub-set of B.",
                            "Algebra of Sets",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        else
            MessageBox.Show("A is not a sub-set of B.",
                        "Algebra of Sets",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    
        if (A.IsSupersetOf(B))
            MessageBox.Show("A is a super-set of B.",
                            "Algebra of Sets",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        else
            MessageBox.Show("A is not a super-set of B.",
                        "Algebra of Sets",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    
        if( A.IsProperSubsetOf(B))
            MessageBox.Show("A is a proper sub-set of B.",
                            "Algebra of Sets",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        else
            MessageBox.Show("A is not a proper sub-set of B.",
                        "Algebra of Sets",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    
        if (A.IsProperSupersetOf(B))
            MessageBox.Show("A is a proper super-set of B.",
                            "Algebra of Sets",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        else
            MessageBox.Show("A is not a proper super set of B.",
                        "Algebra of Sets",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
  2. To execute, press Ctrl + F5
  3. Add a few numbers to the left list box
  4. Add the same numbers to the right list box but in a different order
  5. Click Compare
     
    Sets
     
    Sets
     
    Sets
     
    Sets
  6. Click OK
  7. Close the form and return to your programming environment
  8. To execute again, press Ctrl + F5
  9. Add a few numbers to the left list box
  10. Add some, but not all, of the same numbers to the right list box
  11. Click Compare
     
    Sets
     
    Sets
  12. Click OK
  13. Close the form and return to your programming environment

A Union of Two Sets

Imagine you have two sets A and B defined as follows:

A = { Kevin, Jane, Daniel }
B = { Raul, Kevin, Tiffany, Michael, Jane }

One of the operations you can perform on them is to create a set that contains a list of all their elements. That is, you would get a list that contains elements that are present in each set. If there is an element present in both sets, it would be included only once.

A union of two sets is the list of all elements that belong to both sets. Remember that there is no reason to include an element twice if it already belongs to one of the sets. In algebra, this operation is written as follows:

A ∪ B = { x|x ∈ A or x ∈ B }

This can be visually illustrated as follows:

A Union of Two Sets

To help you unite two sets, the HashSet class is equipped with a method named UnionWith. Its syntax is:

public void UnionWith(IEnumerable<T> other);

This method takes as argument the set whose elements would be combined to those of the set that called the method. Here is an example of calling this method:

using System;
using System.Windows.Forms;
using System.Collections.Generic;

public class SetHasher : Form
{
    Label lblCount;
    Label lblPeople;
    Label lblUnity;
    ListBox lbxNames;
    ListBox lbxPeople;
    ListBox lbxUnity;

    public SetHasher()
    {
        InitializeComponent();
    }

    private void InitializeComponent()
    {
        lbxNames = new ListBox();
        lbxNames.Location = new System.Drawing.Point(12, 12);
        lbxNames.Size = new System.Drawing.Size(120, 120);

        lbxPeople = new ListBox();
        lbxPeople.Location = new System.Drawing.Point(138, 12);
        lbxPeople.Size = new System.Drawing.Size(120, 120);

        lbxUnity = new ListBox();
        lbxUnity.Location = new System.Drawing.Point(264, 12);
        lbxUnity.Size = new System.Drawing.Size(120, 120);

        lblCount = new Label();
        lblCount.AutoSize = true;
        lblCount.Location = new System.Drawing.Point(12, 126);

        lblPeople = new Label();
        lblPeople.AutoSize = true;
        lblPeople.Location = new System.Drawing.Point(138, 126);

        lblUnity = new Label();
        lblUnity.AutoSize = true;
        lblUnity.Location = new System.Drawing.Point(264, 126);

        Text = "Set Hasher";
        MinimizeBox = false;
        MaximizeBox = false;
        StartPosition = FormStartPosition.CenterScreen;
        ClientSize = new System.Drawing.Size(400, 150);
        Load += new EventHandler(FormLoaded);

        Controls.Add(lbxNames);
        Controls.Add(lbxPeople);
        Controls.Add(lbxUnity);
        Controls.Add(lblCount);
        Controls.Add(lblPeople);
        Controls.Add(lblUnity);
    }

    private void FormLoaded(object sender, EventArgs ea)
    {
        HashSet<string> Persons = new HashSet<string>();

        Persons.Add("Kevin Walchild");
        Persons.Add("Jane Overton");
        Persons.Add("Daniel Albertson");
        Persons.Add("Ruth Oyawale");
        Persons.Add("Jane Ouelette");

        foreach (string str in Persons)
            lbxNames.Items.Add(str);
        lblCount.Text = "Number of items: " + Persons.Count.ToString();

        HashSet<string> People = new HashSet<string>();

        People.Add("Antoinette Belton");
        People.Add("Joshua Melmann");
        People.Add("Paul Sullivan");

        foreach (string str in People)
            lbxPeople.Items.Add(str);
        lblPeople.Text = "Number of items: " + People.Count.ToString();

        Persons.UnionWith(People);

        foreach (string str in Persons)
            lbxUnity.Items.Add(str);
        lblUnity.Text = "Number of items: " + Persons.Count.ToString();
    }
}

public class Exercise
{
    [STAThread]
    public static int Main()
    {
        Application.Run(new SetHasher());
        return 0;
    }
}

Collection

It is important to know that this method performs a comparison on the elements of both sets so that the result would not allow any duplicate item.

ApplicationTopic Applied: Creating a Union of Two Sets

  1. Change the design of the form as follows: 
     
    Sets
     
    Control Text Name
    Button Button Union btnUnion
    ListBox List Box   lbxUnion
  2. Double-click the Union button
  3. Implement the event as follows:
    private void btnUnion_Click(object sender, EventArgs e)
    {
        // Because objects in C# are used as references,
        // we will need a brand new set that has the same
        // elements as set A
        HashSet<int> Union = new HashSet<int>();
        
        // Copy the elements of A into the new set
        foreach(int element in A)
            Union.Add(element);
        
        // Unite the new set to B
        Union.UnionWith(B);
    
        lbxUnion.Items.Clear();
    
        foreach (int element in Union)
            lbxUnion.Items.Add(element);
    }
  4. Return to the form
  5. To execute, press Ctrl + F5
  6. Add a few numbers to the left list box 
  7. Add a few numbers to the right list box
     
    Sets
  8. Click Union
     
    Sets
  9. Close the form and return to your programming environment

A Universal Set

If you have two or more sets, a universal set is a list that contains all elements of those sets. For example, if you have three sets A, B, and C, you can write their universal set as:

A ∪ B ∪ C

To programmatically create a universal set, simply call the HashSet<>.UnionWith() method as necessary.

An Intersection of Sets

The intersection between two sets is the list of only members that belong to both sets. That is, the elements that belong to one set but do not belong to the other set are excluded. In algebra, we write it as follows:

A ∩ B = { x|x ∈ A and x ∈ B }

This can be visually illustrated as follows:

An Intersection of Two Sets

To help you reduce a set to its intersecting elements with regards to another set, the HashSet class provides the IntersectWith() method. Its syntax is:

public void IntersectWith(IEnumerable<T> other);

This takes a HashSet object as argument. It finds the elements from the argument that are also present in the variable that called it and it removes the elements that are found in the variable that called it but are not found in the argument.

ApplicationTopic Applied: Creating a Union of Two Sets

  1. Change the design of the form as follows: 
     
    Sets
     
    Control Text Name
    Button Button Intersection btnIntersection
    ListBox ListBox   lbxIntersection
  2. Double-click the Intersection button
  3. Implement the event as follows:
    private void btnIntersection_Click(object sender, EventArgs e)
    {
        HashSet<int> Intersection = new HashSet<int>();
    
        foreach (int element in A)
            Intersection.Add(element);
    
        Intersection.IntersectWith(B);
    
        lbxIntersection.Items.Clear();
    
        foreach (int element in Intersection)
            lbxIntersection.Items.Add(element);
    }
  4. Return to the form and, to execute, press Ctrl + F5
  5. Add a few numbers to the left list box 
  6. Add a few numbers to the right list box,, some of which should also be found in the left list box
     
    Sets
  7. Click Intersection
     
    Sets
  8. Close the form and return to your programming environment

Overlapped Sets

As seen above, the intersecting set is a list of elements shared by two sets. The comparison consists of finding out whether two lists intersect; that is, whether they have at least one common member. To perform this comparison, you can call the Overlaps() method of the HashSet class. Its syntax is:

public bool Overlaps(IEnumerable<T> other);

This method too takes a HashSet object as argument and compares it to the object that called it. If it finds at least one value that exists in both lists, it returns true. If there is no single value that both lists share, the method returns false. Here is an example:

private void FormLoaded(object sender, EventArgs ea)
{
    HashSet<string> Persons = new HashSet<string>();

    Persons.Add("Kevin Walchild");
    Persons.Add("Jane Overton");
    Persons.Add("Daniel Albertson");
    Persons.Add("Ruth Oyawale");
    Persons.Add("Jane Ouelette");
    Persons.Add("Paul Sullivan");

    foreach (string str in Persons)
        lbxNames.Items.Add(str);

    lblCount.Text = "Number of items: " + Persons.Count.ToString();

    HashSet<string> People = new HashSet<string>();

    People.Add("Antoinette Belton");
    People.Add("Joshua Melmann");
    People.Add("Deborah Callum");

    if (People.Overlaps(Persons) == true)
        MessageBox.Show("The Persons and the People lists have at least one name in common.",
                        "Collection Class",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    else
        MessageBox.Show("The Persons and the People lists have no name in common.",
                        "Collection Class",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);


    foreach (string str in People)
        lbxPeople.Items.Add(str);

    lblPeople.Text = "Number of items: " + People.Count.ToString();

    HashSet<string> Students = new HashSet<string>();
    Students.Add("Dominique Donahue");
    Students.Add("Daniel Albertson");
    Students.Add("Michael Sorenso");

    if (Students.Overlaps(Persons))
        MessageBox.Show("The Persons and the Students lists have at least one name in common.",
                        "Collection Class",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    else
        MessageBox.Show("The Persons and the Students lists have no name in common.",
                        "Collection Class",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
}

Hash Set

Hash Set

ApplicationTopic Applied: Checking for a Overlapping Sets

  1. Change the code of the Compare button as follows:
    private void btnCompare_Click(object sender, EventArgs e)
    {
        if (A.SetEquals(B))
            MessageBox.Show("A is equal to B.",
                            "Algebra of Sets",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        else
            MessageBox.Show("A is different from B.",
                        "Algebra of Sets",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    
        if( A.IsSubsetOf(B))
            MessageBox.Show("A is a sub-set of B.",
                            "Algebra of Sets",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        else
            MessageBox.Show("A is not a sub-set of B.",
                        "Algebra of Sets",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    
        if (A.IsSupersetOf(B))
            MessageBox.Show("A is a super-set of B.",
                            "Algebra of Sets",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        else
            MessageBox.Show("A is not a super-set of B.",
                        "Algebra of Sets",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    
        if( A.IsProperSubsetOf(B))
            MessageBox.Show("A is a proper sub-set of B.",
                            "Algebra of Sets",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        else
            MessageBox.Show("A is not a proper sub-set of B.",
                        "Algebra of Sets",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    
        if (A.IsProperSupersetOf(B))
            MessageBox.Show("A is a proper super-set of B.",
                            "Algebra of Sets",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        else
            MessageBox.Show("A is not a proper super set of B.",
                        "Algebra of Sets",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    
        if (A.Overlaps(B))
            MessageBox.Show("A and B overlap.",
                            "Algebra of Sets",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        else
            MessageBox.Show("A and B do not overlap.",
                        "Algebra of Sets",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
  2. To execute, press Ctrl + F5
  3. Add a few numbers to the left list box
  4. Add some different numbers to the right list box
  5. Click Compare
     
    Sets
  6. Click OK
  7. Close the form and return to your programming environment
  8. To execute again, press Ctrl + F5
  9. Add a few numbers to the left list box
  10. Add some, but not all, of the same numbers to the right list box and add some other different numbers to the right list box
  11. Click Intersection
  12. Click Compare
     
    Sets
  13. Click OK
  14. Close the form and return to your programming environment

Set Difference

Consider two sets A and B. The difference between a set A from a set B is the list of elements that are found in set A but are not found in set B. In algebra, this is written as follows:

A - B = { x|x ∈ A and x ∉ B }

This can be illustrated as follows:

The Difference of Two Sets

To let you perform this operation, the HashSet class provides a method named ExceptWith. Its syntax is:

public void ExceptWith(IEnumerable<T> other);

ApplicationTopic Applied: Getting the Difference of Two Sets

  1. Change the design of the form as follows: 
     
    Sets
     
    Control Text Name
    Button Button Difference btnDifference
    ListBox ListBox   lbxDifference
  2. Double-click the Difference button
  3. Implement the event as follows:
    private void btnDifference_Click(object sender, EventArgs e)
    {
        HashSet<int> Difference = new HashSet<int>();
    
        foreach (int element in A)
            Difference.Add(element);
    
        Difference.ExceptWith(B);
    
        lbxDifference.Items.Clear();
    
        foreach (int element in Difference)
            lbxDifference.Items.Add(element);
    }
  4. Return to the form
  5. To execute, press Ctrl + F5
  6. Add a few numbers to the left list box 
  7. Add a few numbers to the right list box, some of which should also be found in the left list box
     
    Sets
  8. Click the Union, the Intersection, and the Difference buttons
     
    Sets
  9. Close the form and return to your programming environment

Symmetric Difference

Consider two sets A and B. The symmetric difference between those sets is the list of elements that belong to each set but do not belong to their intersection. This can be illustrated as follows:

The Symmetric Difference of Two Sets

As you can guess, this is the reverse of the intersection. That is, it the union of the sets excluding their intersection. To let you perform this operation, the HashSet is equipped with the SymmetricExceptWith() method. Its syntax is:

public void SymmetricExceptWith(IEnumerable<T> other);

ApplicationTopic Applied: Getting the Symmetric Difference of Two Sets

  1. Change the design of the form as follows: 
     
    Sets
     
    Control Text Name
    Button Button Symmetric Difference btnSymmetricDifference
    ListBox ListBox   lbxSymmetricDifference
  2. Double-click the Symmetric Difference button
  3. Implement the event as follows:
    private void btnSymmetricDifference_Click(object sender, EventArgs e)
    {
        HashSet<int> SymmetricDifference = new HashSet<int>();
    
        foreach (int element in A)
            SymmetricDifference.Add(element);
    
        SymmetricDifference.SymmetricExceptWith(B);
    
        lbxSymmetricDifference.Items.Clear();
    
        foreach (int element in SymmetricDifference)
            lbxSymmetricDifference.Items.Add(element);
    }
  4. To execute, press Ctrl + F5
  5. Add a few numbers to the left list box 
  6. Add a few numbers to the right list box, some of which should also be found in the left list box
     
    Sets
  7. Click the Union, the Intersection, the Difference, and the Symmetric Difference buttons
     
    Sets
  8. Close the form and return to your programming environment

Deleting Items From a Set

  

Deleting an Item

The HashSet class implements the ICollection<> interface. As such, it inherits the Remove() method that allows you to delete an item from the list. In some cases, you may want to delete an element based on a specific condition. To support this operation, the HashSet class provides the RemoveWhere() method. Its syntax is:

public int RemoveWhere(Predicate<T> match);

This method takes as argument a delegate that specifies what condition would be applied to any element that must be removed.

Clearing a Set

As an implemented of the ICollection interface, the HashSet class inherits the Clear() method that can be used remove all items from a set.

ApplicationTopic Applied: Clearing a Set

  1. Change the design of the form as follows: 
     
    Sets
     
    Control Text Name
    Button Button Clear Left List btnClearLeftList
    Button Button Clear Right List lbxClearRightList
    Button Button Close btnClose
  2. Double-click the Clear Left List button
  3. Implement the event as follows:
    private void btnClearLeftList_Click(object sender, EventArgs e)
    {
        A.Clear();
        lbxNumbersA.Items.Clear();
        txtNumberA.Focus();
    }
  4. Return to the form
  5. Double-click the Clear Right List button
  6. Implement the event as follows:
    private void btnClearRightList_Click(object sender, EventArgs e)
    {
        B.Clear();
        lbxNumbersB.Items.Clear();
        txtNumberB.Focus();
    }
  7. Return to the form
  8. Double-click the Close button
  9. Implement its event as follows:
    private void btnClose_Click(object sender, EventArgs e)
    {
        Close();
    }
  10. To execute, press Ctrl + F5
  11. Close the form and return to your programming environment
 
 
   
 

Home Copyright © 2014, FunctionX