Introduction to Collection Sets

Fundamentals of a Set

Introduction

A set is a collection of values or objects so the list must respond to some Boolean conditions compared to another set. One operation would consist of finding whether two collections are the same because they respond to the same condition. Another operation would consist of finding out whether one list contains the same items as another but contains fewer items than the other collection, and so on. There are rules and conditions a set must follow:

Starting a Set

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

```using static System.Console;
using System.Collections.Generic;

public class Exercise
{
public static void Main()
{
List<string> names = new List<string>();

foreach (string name in names)
WriteLine("Name: " + name);

WriteLine("===============================");
return;
}
}```

This would produce:

```Name: Kevin
Name: Jane
Name: Daniel
Name: Jane
Name: Ruth
Name: Paul
===============================
Press any key to continue . . .```

One of the general rules of a set is that its list should not allow duplicate items (this rule is not strictly followed in algebra but must be followed here).

To support sets, the .NET Framework provides a class named HashSet. This class is defined in the System.Collections.Generic namespace. The HashSet class starts as follows:

```public class HashSet<T> : ICollection<T>,
IEnumerable<T>,
IEnumerable,
ISerializable,
IDeserializationCallback```

Notice that the HashSet class implements:

1. The ICollection interface: This means that the collection is equipped with the ability to add new items and to know the number of items it contains
2. The ISerializable interface: this makes it possible to save (or serialize) the collection
 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.

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:

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:

```using System.Collections.Generic;

public class Exercise
{
public static void Main()
{
HashSet<string> names = new HashSet<string>();
}
}```

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:

To let you add an item to a set, the HashSet class is equipped with a method named Add. Its syntax is:

`public bool Add(T item);`

Pass the desired value as argument to this method. Remember that the class implements the IEnumerable<> interface and therefore the foreach loop. Here are examples of calling the Add() method to populate a set:

```using System.Collections.Generic;

public class Exercise
{
public static void Main()
{
HashSet<string> names = new HashSet<string>();

}
}```

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 (but) the compiler does not throw an exception

Accessing Each Element of a Set

The HashSet class implements the IEnumerable<T> and the IEnumerable interfaces. This makes it possible to use the foreach loop to access each item of a set. Here is an example:

```using static System.Console;
using System.Collections.Generic;

public class Exercise
{
public static void Main()
{
HashSet<string> types = new HashSet<string>();

Title = "Playground Accessories";
WriteLine("Playground Accessories");

WriteLine("-------------------------------");

foreach (string equipment in types)
WriteLine("Equipment: " + equipment);

WriteLine("===============================");
return;
}
}```

This would produce:

```Playground Accessories
-------------------------------
Equipment: Swing
Equipment: Seesaw
Equipment: Jungle Gym
Equipment: Spring Rider
Equipment: Chin-Up Bars
===============================
Press any key to continue . . .```

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 if 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 determined (or the 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 static System.Console;
using System.Collections.Generic;

public class Exercise
{
public static void Main()
{
HashSet<string> names = new HashSet<string>();

Title = "Names";
WriteLine("Names");

WriteLine("-------------------------------");

WriteLine("This set contains {0} elemnts.", names.Count);

WriteLine("===============================");
return;
}
}```

This would produce:

```Names
-------------------------------
This set contains 5 elemnts.
===============================
Press any key to continue . . .```

Notice that the property produces the actual number of items in the collection, excluding those that were not added (because of duplication issues).

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:

```using static System.Console;
using System.Collections.Generic;

public class Exercise
{
public static void Main()
{
HashSet<string> names = new HashSet<string>();

Title = "Names";
WriteLine("Names");

WriteLine("-------------------------------");

WriteLine("This set contains Jane: {0}.", names.Contains("Jane"));
WriteLine("This set contains Frank {0}.", names.Contains("Frank"));

WriteLine("===============================");
return;
}
}```

This would produce:

```Names
-------------------------------
This set contains Jane: True.
This set contains Frank False.
===============================
Press any key to continue . . .```

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 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. This can be illustrated as follows:

To let you assign the values of one HashSet collection to another, the class provides another constructor. Its 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:

```using static System.Console;
using System.Collections.Generic;

public class Exercise
{
public static void Main()
{
HashSet<string> types = new HashSet<string>();

Title = "Names";
WriteLine("Names");

WriteLine("-------------------------------");

HashSet<string> recreation = new HashSet<string>(types);

foreach (string obj in recreation)
WriteLine("Equipment: {0}", obj);

WriteLine("===============================");
return;
}
}```

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 static System.Console;
using System.Collections.Generic;

public class Exercise
{
public static void Main()
{
HashSet<string> types = new HashSet<string>();

Title = "Playground Accessories";
WriteLine("Playground Accessories");

WriteLine("-------------------------------");

HashSet<string> recreation = new HashSet<string>(types);

foreach (string obj in recreation)
WriteLine("Equipment: {0}", obj);

WriteLine("-------------------------------");

foreach (string obj in recreation)
WriteLine("Equipment: {0}", obj);

WriteLine("===============================");
return;
}
}```

This would produce:

```Playground Accessories
-------------------------------
Equipment: Swing
Equipment: Seesaw
Equipment: Jungle Gym
Equipment: Spring Rider
Equipment: Chin-Up Bars
-------------------------------
Equipment: Swing
Equipment: Seesaw
Equipment: Jungle Gym
Equipment: Spring Rider
Equipment: Chin-Up Bars
Equipment: Playground Slide
Equipment: Merry-Go-Round
===============================
Press any key to continue . . .```

Operations on Sets

Comparing Sets For Equality

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

```A = { Connecticut, Maine, Massachusetts, New Hampshire, Rhode Island, Vermont }
B = { Massachusetts, Vermont, Connecticut, New Hampshire, Rhode Island, Maine }```

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:

```using static System.Console;
using System.Collections.Generic;

public class Exercise
{
public static void Main()
{
Title = "Country's Regions";
WriteLine("Country's Regions");

HashSet<string> census = new HashSet<string>();
HashSet<string> omb = new HashSet<string>();
HashSet<string> eastCoast = new HashSet<string>();

WriteLine("===============================================================================");

if (census.SetEquals(omb) == true)
WriteLine("The Census Bureau and the Office of Management and Budget use the same north - east states for their first statistical region.");
else
WriteLine("The Census Bureau and the Office of Management and Budget use different states for their statistical analyses.");

WriteLine("-------------------------------------------------------------------------------");
if (census.SetEquals(eastCoast) == true)
WriteLine("The Census Bureau uses all of the states of the east coast for its projections.");
else
WriteLine("The Census Bureau uses only some of the coastal states for statistical purposes.");

WriteLine("===============================================================================");
return;
}
}```

This would produce:

```Country's Regions
===============================================================================
The Census Bureau and the Office of Management and Budget use the same north - e
ast states for their first statistical region.
-------------------------------------------------------------------------------
The Census Bureau uses only some of the coastal states for statistical purposes.

===============================================================================
Press any key to continue . . .```

A Subset of Another Set

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

```A = { New York, New Jersey, Pennsylvania }
B = { Delaware, Pennsylvania, District of Columbia, New York, Maryland, New Jersey }```

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:

` { New York, New Jersey, Pennsylvania } ⊂ { Delaware, Pennsylvania, District of Columbia, New York, Maryland, New Jersey }`

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

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 is equipped with a method named IsSubsetOf. Its syntax is:

`public bool IsSubsetOf(IEnumerable<T> other);`

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

```using static System.Console;
using System.Collections.Generic;

public class Exercise
{
public static void Main()
{
Title = "Country's Regions";
WriteLine("Country's Regions");

HashSet<string> censusMidAtlantic = new HashSet<string>();
HashSet<string> beaMideast = new HashSet<string>();

WriteLine("===============================================================================");

if (censusMidAtlantic.IsSubsetOf(beaMideast))
WriteLine("The Mid-Atlantic region of the Census Bureau is a sub-set of the Mideast region of the Bureau of Economic Analysis.");
else
WriteLine("The Mideast region of the Bureau of Economic Analysis has more states than the Mid-Atlantic region of the Census Bureau.");

WriteLine("===============================================================================");
return;
}
}```

This would produce:

```Country's Regions
===============================================================================
The Mid-Atlantic region of the Census Bureau is a sub-set of the Mideast region
of the Bureau of Economic Analysis.
===============================================================================
Press any key to continue . . .```

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.

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. Consider the following illustration of sets:

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 proper subset of set B. This can be illustrated as follows:

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

`public bool IsProperSubsetOf(IEnumerable<T> other);`

This method takes a HashSet list as argument 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:

```using static System.Console;
using System.Collections.Generic;

public class Exercise
{
public static void Main()
{
Title = "Country's Regions";
WriteLine("Country's Regions");

HashSet<string> censusMidAtlantic = new HashSet<string>();
HashSet<string> beaMideast = new HashSet<string>();

WriteLine("===============================================================================");

if (censusMidAtlantic.IsProperSubsetOf(beaMideast))
WriteLine("The Mid-Atlantic region of the Census Bureau is a proper sub-set of the Mideast region of the Bureau of Economic Analysis.");
else
WriteLine("The Mid-Atlantic region of the Census Bureau is NOT a proper sub-set of the Mideast region of the Bureau of Economic Analysis.");

WriteLine("------------------------------------------------------------------------------");

if (censusMidAtlantic.IsProperSubsetOf(beaMideast))
WriteLine("The Mid-Atlantic region of the Census Bureau is a proper sub-set of the Mideast region of the Bureau of Economic Analysis.");
else
WriteLine("The Mid-Atlantic region of the Census Bureau is NOT a proper sub-set of the Mideast region of the Bureau of Economic Analysis.");

WriteLine("------------------------------------------------------------------------------");

if (censusMidAtlantic.IsProperSubsetOf(beaMideast))
WriteLine("The Mid-Atlantic region of the Census Bureau is a proper sub-set of the Mideast region of the Bureau of Economic Analysis.");
else
WriteLine("The Mideast region of the Bureau of Economic Analysis has more states than the Mid-Atlantic region of the Census Bureau.");

WriteLine("===============================================================================");
return;
}
}```

This would produce:

```Country's Regions
===============================================================================
The Mid-Atlantic region of the Census Bureau is NOT a proper sub-set of the Mide
ast region of the Bureau of Economic Analysis.
------------------------------------------------------------------------------
The Mid-Atlantic region of the Census Bureau is a proper sub-set of the Mideast
region of the Bureau of Economic Analysis.
------------------------------------------------------------------------------
The Mid-Atlantic region of the Census Bureau is a proper sub-set of the Mideast
region of the Bureau of Economic Analysis.
===============================================================================
Press any key to continue . . .```

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. Here are examples of calling this method:

```using static System.Console;
using System.Collections.Generic;

public class Exercise
{
public static void Main()
{
Title = "Country's Regions";
WriteLine("Country's Regions");

HashSet<string> beaMideast = new HashSet<string>();
HashSet<string> standardRegion2 = new HashSet<string>();
HashSet<string> censusMidAtlantic = new HashSet<string>();

WriteLine("===============================================================================");

if (beaMideast.IsSupersetOf(censusMidAtlantic) )
WriteLine("The Mid-Atlantic region of the Bureau of Economic Analysis is a super-set of the Mideast region of the Census Bureau.");
else
WriteLine("The Mid-Atlantic region of the Bureau of Economic Analysis is NOT a super-set of the Mideast region of the Census Bureau.");

WriteLine("------------------------------------------------------------------------------");

if (standardRegion2.IsSupersetOf(censusMidAtlantic))
WriteLine("Region II of the Office of Management and Budget (OMB) is a super-set of the Mideast region of the Census Bureau.");
else
WriteLine("Region II of the Office of Management and Budget (OMB) is NOT a super-set of the Mideast region of the Census Bureau.");

WriteLine("===============================================================================");
return;
}
}```

This would produce

```Country's Regions
===============================================================================
The Mid-Atlantic region of the Bureau of Economic Analysis is a super-set of the
Mideast region of the Census Bureau.
------------------------------------------------------------------------------
Region II of the Office of Management and Budget (OMB) is NOT a super-set of the
Mideast region of the Census Bureau.
===============================================================================
Press any key to continue . . .```

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 proper 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);`

Here is an example:

```using static System.Console;
using System.Collections.Generic;

public class Exercise
{
public static void Main()
{
Title = "Country's Regions";
WriteLine("Country's Regions");

HashSet<string> beaMideast = new HashSet<string>();
HashSet<string> censusMidAtlantic = new HashSet<string>();

WriteLine("===============================================================================");

if (beaMideast.IsSupersetOf(censusMidAtlantic) == true)
WriteLine("The Mid-Atlantic region of the Bureau of Economic Analysis is a super-set of the Mideast region of the Census Bureau.");
else
WriteLine("The Mid-Atlantic region of the Bureau of Economic Analysis is NOT a super-set of the Mideast region of the Census Bureau.");

WriteLine("------------------------------------------------------------------------------");

if (beaMideast.IsProperSupersetOf(censusMidAtlantic))
WriteLine("The Mid-Atlantic region of the Bureau of Economic Analysis is a PROPER super-set of the Mideast region of the Census Bureau.");
else
WriteLine("The Mid-Atlantic region of the Bureau of Economic Analysis is NOT a PROPER super-set of the Mideast region of the Census Bureau.");

WriteLine("------------------------------------------------------------------------------");

if (beaMideast.IsProperSupersetOf(censusMidAtlantic))
WriteLine("The Mid-Atlantic region of the Bureau of Economic Analysis is a PROPER super-set of the Mideast region of the Census Bureau.");
else
WriteLine("The Mid-Atlantic region of the Bureau of Economic Analysis is NOT a PROPER super-set of the Mideast region of the Census Bureau.");

WriteLine("===============================================================================");
return;
}
}```

This would produce:

```Country's Regions
===============================================================================
The Mid-Atlantic region of the Bureau of Economic Analysis is a super-set of the
Mideast region of the Census Bureau.
------------------------------------------------------------------------------
The Mid-Atlantic region of the Bureau of Economic Analysis is NOT a PROPER super
-set of the Mideast region of the Census Bureau.
------------------------------------------------------------------------------
The Mid-Atlantic region of the Bureau of Economic Analysis is a PROPER super-set
of the Mideast region of the Census Bureau.
===============================================================================
Press any key to continue . . .```

A Union of Two Sets

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

```A = { Colorado, Montana, Wyoming, Utah, New Mexico, Arizona, Nevada, Idaho }
B = { Wyoming, Colorado, Oklahoma, Kansas, Utah }```

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:

To help you unite two sets, the HashSet class is equipped with a method named Union. 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 static System.Console;
using System.Collections.Generic;

public class Exercise
{
public static void Main()
{
string census = string.Empty;
string circuit = string.Empty;
HashSet<string> censusMountain = new HashSet<string>();
HashSet<string> courtOfAppealsCircuit10 = new HashSet<string>();

foreach (string state in censusMountain)
census += state + ", ";

WriteLine("Census Bureau - Mountain: {0}", census.Substring(0, census.Length - 2));

foreach (string state in courtOfAppealsCircuit10)
circuit += state + ", ";

WriteLine("Court of Appeals - Circuit 10: {0}", circuit.Substring(0, circuit.Length - 2));

WriteLine("------------------------------------------------------------------------------");

censusMountain.UnionWith(courtOfAppealsCircuit10);

WriteLine("Union of Mountain Region of Census and Court of Appeals Circuit 10");

foreach (string state in censusMountain)
WriteLine("State: " + state);

WriteLine("===============================================================================");
return;
}
}```

This would produce:

```Census Bureau - Mountain: Colorado, Montana, Wyoming, Utah, New Mexico, Arizona,
Court of Appeals - Circuit 10: New Mexico, Wyoming, Colorado, Oklahoma, Kansas,
Utah
------------------------------------------------------------------------------
Union of Mountain Region of Census and Court of Appeals Circuit 10
State: Montana
State: Wyoming
State: Utah
State: New Mexico
State: Arizona
State: Idaho
State: Oklahoma
State: Kansas
===============================================================================
Press any key to continue . . .```

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.

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 illustrated as follows:

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

`public void IntersectWith(IEnumerable<T> other);`

This method takes a HashSet collection as argument. It finds the elements from the argument that are (the elements) 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. Here is an example:

```using static System.Console;
using System.Collections.Generic;

public class Exercise
{
public static void Main()
{
string census = string.Empty;
string circuit = string.Empty;
HashSet<string> censusMountain = new HashSet<string>();
HashSet<string> courtOfAppealsCircuit10 = new HashSet<string>();

Title = "Country's Statistics";
WriteLine("Country's Statistics");
WriteLine("===============================================================================");

foreach (string state in censusMountain)
census += state + ", ";

WriteLine("Census Bureau - Mountain: {0}", census.Substring(0, census.Length - 2));

foreach (string state in courtOfAppealsCircuit10)
circuit += state + ", ";

WriteLine("-----------------------------------------------------------------------");

WriteLine("Court of Appeals - Circuit 10: {0}", circuit.Substring(0, circuit.Length - 2));

censusMountain.IntersectWith(courtOfAppealsCircuit10);

WriteLine("-----------------------------------------------------------------------");

WriteLine("The common states between Mountain Region of Census and Court of Appeals Circuit10 are:");

foreach (string state in censusMountain)
WriteLine("State: " + state);

WriteLine("===============================================================================");
return;
}
}```

This would produce:

```Country's Statistics
===============================================================================
Census Bureau - Mountain: Colorado, Montana, Wyoming, Utah, New Mexico, Arizona,
-----------------------------------------------------------------------
Court of Appeals - Circuit 10: New Mexico, Wyoming, Colorado, Oklahoma, Kansas,
Utah
-----------------------------------------------------------------------
The common states between Mountain Region of Census and Court of Appeals Circuit
10 are:
State: Wyoming
State: Utah
State: New Mexico
===============================================================================
Press any key to continue . . .```

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 support this comparison, the HashSet class is equipped with a method named Overlaps. 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:

```using static System.Console;
using System.Collections.Generic;

public class Exercise
{
public static void Main()
{
string bea = string.Empty;
string census = string.Empty;
string circuit = string.Empty;
HashSet<string> beaMideast = new HashSet<string>();
HashSet<string> censusMountain = new HashSet<string>();
HashSet<string> courtOfAppealsCircuit10 = new HashSet<string>();

Title = "Country's Statistics";
WriteLine("Country's Statistics");
WriteLine("===============================================================================");

foreach (string state in beaMideast)
bea += state + ", ";

WriteLine("Bureau of Economic Analysis - Mideast Region: {0}", bea.Substring(0, bea.Length - 2));

foreach (string state in censusMountain)
census += state + ", ";

WriteLine("-----------------------------------------------------------------------------");

WriteLine("Census Bureau - Mountain: {0}", census.Substring(0, census.Length - 2));

foreach (string state in courtOfAppealsCircuit10)
circuit += state + ", ";

WriteLine("-----------------------------------------------------------------------------");

WriteLine("Court of Appeals - Circuit 10: {0}", circuit.Substring(0, circuit.Length - 2));

WriteLine("-----------------------------------------------------------------------------");

if (censusMountain.Overlaps(courtOfAppealsCircuit10))
WriteLine("The Mountain Region of the Census Bureau and the 10th Circuit of the Court of Appeals have at least one state in common.");
else
WriteLine("The Mountain Region of the Census Bureau and the 10th Circuit of the Court of Appeals have NO state in common.");

WriteLine("-----------------------------------------------------------------------------");

if (beaMideast.Overlaps(courtOfAppealsCircuit10))
WriteLine("The Mideast region of the Bureau of Economic Analysis and the 10th Circuit of the Court of Appeals have at least one state in common.");
else
WriteLine("The Mideast region of the Bureau of Economic Analysis and the 10th Circuit of the Court of Appeals DO NOT have ANY state in common.");

WriteLine("===============================================================================");
return;
}
}```

This would produce:

```Country's Statistics
===============================================================================
Bureau of Economic Analysis - Mideast Region: Pennsylvania, New York, New Jersey

-----------------------------------------------------------------------------
Census Bureau - Mountain: Colorado, Montana, Wyoming, Utah, New Mexico, Arizona,
-----------------------------------------------------------------------------
Court of Appeals - Circuit 10: New Mexico, Wyoming, Colorado, Oklahoma, Kansas,
Utah
-----------------------------------------------------------------------------
The Mountain Region of the Census Bureau and the 10th Circuit of the Court of Ap
peals have at least one state in common.
-----------------------------------------------------------------------------
The Mideast region of the Bureau of Economic Analysis and the 10th Circuit of th
e Court of Appeals DO NOT have ANY state in common.
===============================================================================
Press any key to continue . . .```

The Difference of Two Sets

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:

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

`public void ExceptWith(IEnumerable<T> other);`

Here is an example:

```using static System.Console;
using System.Collections.Generic;

public class Exercise
{
public static void Main()
{
string bea = string.Empty;
string census = string.Empty;
string circuit = string.Empty;
HashSet<string> censusMountain = new HashSet<string>();
HashSet<string> courtOfAppealsCircuit10 = new HashSet<string>();

Title = "Country's Statistics";
WriteLine("Country's Statistics");
WriteLine("===============================================================================");

foreach (string state in censusMountain)
census += state + ", ";

WriteLine("<b>Census Bureau - Mountain: {0}", census.Substring(0, census.Length - 2));

foreach (string state in courtOfAppealsCircuit10)
circuit += state + ", ";

WriteLine("-----------------------------------------------------------------------------");

WriteLine("Court of Appeals - Circuit 10: {0}", circuit.Substring(0, circuit.Length - 2));

censusMountain.ExceptWith(courtOfAppealsCircuit10);

WriteLine("-----------------------------------------------------------------------------");

WriteLine("Exception Between Mountain region of the Census Bureau and Court of Appeals Circuit 10:");

foreach (string state in censusMountain)
WriteLine("State: " + state);

WriteLine("===============================================================================");
return;
}
}```

This would produce:

```Country's Statistics
===============================================================================
Census Bureau - Mountain: Colorado, Montana, Wyoming, Utah, New Mexico, Arizo
-----------------------------------------------------------------------------
Court of Appeals - Circuit 10: New Mexico, Wyoming, Colorado, Oklahoma, Kansas,
Utah
-----------------------------------------------------------------------------
Exception Between Mountain region of the Census Bureau and Court of Appeals Circ
uit 10:
State: Montana
State: Arizona
State: Idaho
===============================================================================
Press any key to continue . . .```

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:

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 a method named SymmetricExceptWith. Its syntax is:

`public void SymmetricExceptWith(IEnumerable<T> other);`

Here is an example:

```using static System.Console;
using System.Collections.Generic;

public class Exercise
{
public static void Main()
{
string census = string.Empty;
string circuit = string.Empty;
HashSet<string> censusMountain = new HashSet<string>();
HashSet<string> courtOfAppealsCircuit10 = new HashSet<string>();

Title = "Country's Statistics";
WriteLine("Country's Statistics");
WriteLine("===============================================================================");

foreach (string state in censusMountain)
census += state + ", ";

WriteLine("Census Bureau - Mountain: {0}", census.Substring(0, census.Length - 2));

foreach (string state in courtOfAppealsCircuit10)
circuit += state + ", ";

WriteLine("-----------------------------------------------------------------------------");

WriteLine("Court of Appeals - Circuit 10: {0}", circuit.Substring(0, circuit.Length - 2));

WriteLine("-----------------------------------------------------------------------------");

censusMountain.SymmetricExceptWith(courtOfAppealsCircuit10);

WriteLine("Symmetric Exception Between Mountain region of the Census Bureau and Court of Appeals Circuit 10:");

foreach (string state in censusMountain)
WriteLine("State: " + state);

WriteLine("===============================================================================");
return;
}
}```

This would produce:

```Country's Statistics
===============================================================================
Census Bureau - Mountain: Colorado, Montana, Wyoming, Utah, New Mexico, Arizona,
-----------------------------------------------------------------------------
Court of Appeals - Circuit 10: New Mexico, Wyoming, Colorado, Oklahoma, Kansas,
Utah
-----------------------------------------------------------------------------
Symmetric Exception Between Mountain region of the Census Bureau and Court of Ap
peals Circuit 10:
State: Oklahoma
State: Montana
State: Kansas
State: Arizona
State: Idaho
===============================================================================
Press any key to continue . . .```

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. Here is an example:

```using static System.Console;
using System.Collections.Generic;

public class Exercise
{
public static void Main()
{
Title = "United States Statistics";

WriteLine("United States Statistics");

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

WriteLine("=========================");
foreach (string state in eastCoast)
WriteLine("State: " + state);

eastCoast.Remove("Delaware");

WriteLine("------------------------");
foreach (string state in eastCoast)
WriteLine("State: " + state);

WriteLine("================================");
return;
}
}```

This would produce:

```United States Statistics
=========================
State: New Hampshire
State: Vermont
State: Massachusetts
State: Rhode Island
State: Connecticut
State: New Jersey
State: Delaware
State: Maryland
State: Virginia
State: North Carolina
State: South Carolina
State: Georgia
State: Florida
------------------------
State: New Hampshire
State: Vermont
State: Massachusetts
State: Rhode Island
State: Connecticut
State: New Jersey
State: Maryland
State: Virginia
State: North Carolina
State: South Carolina
State: Georgia
State: Florida
================================
Press any key to continue . . .```

In some cases, you may want to delete an element based on a specific condition. To support this operation, the HashSet class provides a method named RemoveWhere. 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. Here is an example that asks the compiler to remove strings that contain a space:

```using static System.Console;
using System.Collections.Generic;

public class Exercise
{
public static void Main()
{
Title = "United States Statistics";

WriteLine("United States Statistics");

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

WriteLine("=========================");
foreach (string state in eastCoast)
WriteLine("State: " + state);

eastCoast.RemoveWhere(name => name.Contains(" "));

WriteLine("------------------------");

foreach (string state in eastCoast)
WriteLine("State: " + state);

WriteLine("================================");
return;
}
}```

This would produce:

```United States Statistics
=========================
State: New Hampshire
State: Vermont
State: Massachusetts
State: Rhode Island
State: Connecticut
State: New Jersey
State: Delaware
State: Maryland
State: Virginia
State: North Carolina
State: South Carolina
State: Georgia
State: Florida
------------------------
State: Vermont
State: Massachusetts
State: Connecticut
State: Delaware
State: Maryland
State: Virginia
State: Georgia
State: Florida
================================
Press any key to continue . . .```

Clearing a Set

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