Sabari M Sabari M
Updated date Jan 15, 2023
In this blog, we will learn how to merge two hash sets in C#

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

Sabari M
Sabari M
Software Professional, India

IT professional with 15+ years of experience in Microsoft Technologies with a strong base in Microsoft .NET (C#.Net, ASP.Net MVC, ASP.NET WEB API, Webservices,...Read More

https://www.techieclues.com/profile/alagu-mano-sabari-m

Comments (0)

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