Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#
hashset
communitycreator

How to copy a HashSet to an existing array in C#

Surabhi Sharma

CopyTo() method

The HashSet<T> generic class in the System.Collections.Generic namespace provides the CopyTo() method with multiple overloads, which can be used to copy a HashSet to an existing array in C#.

Syntax

public void CopyTo (T[] array);

Arguments

  • This method takes a one-dimensional array as input, where the elements will be copied from HashSet<T>.

Return value

This method does not return any value.

Things to Note

  • This method throws an exception if the input array is null or the number of elements in HashSet<T> is greater than the total number of spaces available in the destination array.

  • This method works on one-dimensional arrays.

  • This operation does not change the state of the HashSet<T>.

  • This is an O(n) operation, where n is the number of elements in the HashSet<T>.

Copying HashSet elements using CopyTo() method

Code

We have first included the System.Collections.Generic namespace in the example below.

using System;
using System.Collections.Generic;

class HashSetCopy
{
    static void Main()
    {
        HashSet<string> months = new HashSet<string>();
        months.Add("March");
        months.Add("April");
        months.Add("May");
        months.Add("June");

        Console.WriteLine("HashSet Items : ");
        PrintSet(months);
        string[] hashSetArray = new string[4];

        Console.WriteLine("Array Items before Copy : {0}", string.Join(",", hashSetArray));
        months.CopyTo(hashSetArray);
        Console.WriteLine("Array Items after Copy : {0}", string.Join(",", hashSetArray));

    }

    private static void PrintSet(HashSet<string> set)
    {
      Console.Write("{");
      foreach (var i in set)
      {
          Console.Write(" {0}", i);
      }
      Console.WriteLine(" }");
    }
}

Explanation

  • In this example, we create a HashSet of strings to store month names, and add the names of four months to it: "March", "April", "May", and "June".

  • After we add the elements, we print all the elements present in the HashSet.

  • After this, we create a new array hashSetArray of strings with a size of 4 elements.

  • We now copy all the HashSet elements to this array with the CopyTo() method.

    months.CopyTo(hashSetArray);
    
  • We then print the elements of the array, and we can observe that the array contains all the HashSet elements.

Output

The program prints the output below and exits.

HashSet Items : 
{ March April May June }
Array Items before Copy : ,,,
Array Items after Copy : March,April,May,June

RELATED TAGS

c#
hashset
communitycreator
RELATED COURSES

View all Courses

Keep Exploring