System.Collections.Generic.ISet<T>

Namespace: System.Collections.Generic
Assembly: mscorlib.dll

Interface

Represents a collection of elements that contains no duplicate values.

The ISet<T> interface is implemented by collection types that represent a mathematical set. A set is a collection that contains no duplicate elements. Sets are useful for performing set operations such as union, intersection, and difference.

When you implement the ISet<T> interface, the following methods are important:

Members

Methods

Add (T element)
Adds an element to the set.
Remove (T element)
Removes an element from the set.
Contains (T element)
Determines whether the set contains a specific value.
UnionWith (IEnumerable<T> other)
Modifies the current set to contain all elements from the specified collection.
IntersectWith (IEnumerable<T> other)
Modifies the current set to contain only elements that are also in the specified collection.
ExceptWith (IEnumerable<T> other)
Modifies the current set to remove all elements that are also in the specified collection.
SymmetricExceptWith (IEnumerable<T> other)
Modifies the current set to contain only elements that are present in either the current set or the specified collection, but not in both.

Inherited Members from IEnumerable<T>

GetEnumerator ()
Returns an enumerator that iterates through the collection.

Inherited Members from IEnumerable

GetEnumerator ()
Returns an enumerator that iterates through a collection.

Example

The following example demonstrates how to use HashSet<T>, which implements ISet<T>, to perform set operations.

using System; using System.Collections.Generic; public class Example { public static void Main() { // Create two sets ISet<int> setA = new HashSet<int> { 1, 2, 3, 4, 5 }; ISet<int> setB = new HashSet<int> { 4, 5, 6, 7, 8 }; Console.WriteLine("Set A: " + string.Join(", ", setA)); Console.WriteLine("Set B: " + string.Join(", ", setB)); // Union ISet<int> unionSet = new HashSet<int>(setA); unionSet.UnionWith(setB); Console.WriteLine("Union (A U B): " + string.Join(", ", unionSet)); // Output: 1, 2, 3, 4, 5, 6, 7, 8 // Intersection ISet<int> intersectionSet = new HashSet<int>(setA); intersectionSet.IntersectWith(setB); Console.WriteLine("Intersection (A ∩ B): " + string.Join(", ", intersectionSet)); // Output: 4, 5 // Difference (A - B) ISet<int> differenceSetA = new HashSet<int>(setA); differenceSetA.ExceptWith(setB); Console.WriteLine("Difference (A - B): " + string.Join(", ", differenceSetA)); // Output: 1, 2, 3 // Symmetric Difference (A Δ B) ISet<int> symmetricDifferenceSet = new HashSet<int>(setA); symmetricDifferenceSet.SymmetricExceptWith(setB); Console.WriteLine("Symmetric Difference (A Δ B): " + string.Join(", ", symmetricDifferenceSet)); // Output: 1, 2, 3, 6, 7, 8 } }