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:
Add(T element)
: Adds an element to the set. Returns true
if the element was added successfully, and false
if the element is already in the set.Remove(T element)
: Removes an element from the set. Returns true
if the element was removed successfully, and false
if the element was not found in the set.Contains(T element)
: Checks if an element is present in the set.UnionWith(IEnumerable<T> other)
: Modifies the current set so that it contains all elements that are present in both the current set and the specified collection.IntersectWith(IEnumerable<T> other)
: Modifies the current set so that it contains only elements that are present in both the current set and the specified collection.ExceptWith(IEnumerable<T> other)
: Modifies the current set so that it contains only elements that are present in the current set and not in the specified collection.SymmetricExceptWith(IEnumerable<T> other)
: Modifies the current set so that it contains only elements that are present in either the current set or the specified collection, but not in both.IEnumerable<T>
IEnumerable
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
}
}