Initializing HashSet in C#



To initialize a HashSet.

var h = new HashSet<string>(arr1);

Above, we have set an array in the HashSet. The following is the array −

string[] arr1 = {    "electronics",    "accessories”,    "electronics", };

The following is an example showing how to implement HashSet in C# −

Example

using System; using System.Collections.Generic; using System.Linq; class Program {    static void Main() {       string[] arr1 = {          "electronics",          "accessories”,          "electronics",       };       Console.WriteLine(string.Join(",", arr1));       // HashSet       var h = new HashSet(arr1);       // eliminates duplicate words       string[] arr2 = h.ToArray();       Console.WriteLine(string.Join(",", arr2));    } }
Updated on: 2020-06-21T15:50:18+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements