Wednesday 5 October 2016

Hash Set best example in C#

Example Here
HashSet is an optimized set collection. It helps eliminates duplicate strings or elements in an array. It provides a simple syntax for taking the union of elements in a set. This is performed in its constructor.

C# program that uses HashSet on duplicates

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

class Program
{
    static void Main()
    {
 // Input array that contains three duplicate strings.
 string[] array1 = { "cat", "dog", "cat", "leopard", "tiger", "cat" };

 // Display the array.
 Console.WriteLine(string.Join(",", array1));

 // Use HashSet constructor to ensure unique strings.
 var hash = new HashSet<string>(array1);

 // Convert to array of strings again.
 string[] array2 = hash.ToArray();

 // Display the resulting array.
 Console.WriteLine(string.Join(",", array2));
    }
}

Output

cat,dog,cat,leopard,tiger,cat
cat,dog,leopard,tiger

No comments:

Post a Comment