HashSet in C#

CsharpProgrammingServer Side Programming

HashSet in C# eliminates duplicate strings or elements in an array.In C#, it is an optimized set collection.

Let us see an example to remove duplicate strings using C# HashSet. Here, we have duplicate elements −

Example

 Live Demo

using System;
using System.Collections.Generic;
using System.Linq;

class Program {
   static void Main() {

      string[] arr1 = {
         "bus",
         "truck",
         "bus",
         "car",
         "truck"
      };

      Console.WriteLine(string.Join(",", arr1));

      // HashSet
      var h = new HashSet(arr1);
      // eliminates duplicate words
      string[] arr2 = h.ToArray();
      Console.WriteLine(string.Join(",", arr2));
   }
}

Output

bus,truck,bus,car,truck
bus,truck,car

To declare HashSet −

var h = new HashSet(arr1);

Now set it on the array to remove the duplicate words −

string[] arr2 = h.ToArray();
raja
Published on 10-Aug-2018 08:17:37
Advertisements