C# Set Explained: Usage & Examples

In C#, a set is a collection data structure used to store a unique group of elements. Sets do not allow duplicate elements; each element is unique.

In C#, you can use the HashSet class to represent a set collection, which includes various methods and properties for managing elements such as adding, deleting, and checking for the existence of elements.

Here is an example code for creating and manipulating set collections using the HashSet class.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        HashSet<int> set = new HashSet<int>();

        // 向set集合中添加元素
        set.Add(1);
        set.Add(2);
        set.Add(3);

        // 删除元素
        set.Remove(2);

        // 检查元素是否存在
        if (set.Contains(1))
        {
            Console.WriteLine("Element 1 exists in the set.");
        }

        // 遍历set集合中的元素
        foreach (int element in set)
        {
            Console.WriteLine(element);
        }
    }
}

By using the HashSet class, it is easy to create and manipulate set collections, achieving unique management of collection elements.

bannerAds