TechieClues TechieClues
Updated date Jan 15, 2023
In this blog, we will learn how to merge two hash sets in C#
  • 2.3k
  • 0
  • 0

We have many ways in C# to merge the HashSet<T> easily. We will merge HashSet<T> using the below options in C#,

  • HashSet<T>.UnionWith() Method
  • foreach loop

 Using HashSet<T>.UnionWith() Method

The easiest way to merge one HashSet<T> with another HashSet<T> is by using HashSet<T>.UnionWith() in C#. We can as many elements or values in the hash set in C# and we can merge them using UnionWidth()

using System;
using System.Collections.Generic;

namespace MergeHashSets
{
    class Program
    {
        public static void Main()
        {
            // HashSet 1
            HashSet<int> hashSet1 = new HashSet<int>() { 1, 2, 3, 4 };
            // HashSet 2
            HashSet<int> hashSet2 = new HashSet<int>() { 3, 5, 6, 7, 1 };

            hashSet1.UnionWith(hashSet2);

            Console.WriteLine(String.Join(", ", hashSet1));
            Console.ReadKey();
        }
    }
}

Output:

1, 2, 3, 4, 5, 6, 7

Using foreach loop

We can also use the foreach loop to merge two HashSet<T> in C# as shown below,

using System;
using System.Collections.Generic;

namespace MergeHashSets
{
    class Program
    {
        public static void Main()
        {
            // HashSet 1
            HashSet<int> hashSet1 = new HashSet<int>() { 1, 2, 3, 4 };
            // HashSet 2
            HashSet<int> hashSet2 = new HashSet<int>() { 3, 5, 6, 7, 1 };

            foreach (var hashset in hashSet2)
            {
                hashSet1.Add(hashset);
            }

            Console.WriteLine(String.Join(", ", hashSet1));
            Console.ReadKey();
        }
    }
}

 Output:

1, 2, 3, 4, 5, 6, 7

ABOUT THE AUTHOR

TechieClues
TechieClues

I specialize in creating and sharing insightful content encompassing various programming languages and technologies. My expertise extends to Python, PHP, Java, ... For more detailed information, please check out the user profile

https://www.techieclues.com/profile/techieclues

Comments (0)

There are no comments. Be the first to comment!!!