Share your content and reach out to more developers by submitting them at Abundantcode.com - Developer Community Site

Using HashSet to remove duplicates from array in C#

If you want to remove duplicates from an array in C# , one of the options is to use HashSet as shown below.

How to remove duplicates from an array in C# using HashSet?

 

using System;
using System.Collections.Generic;
namespace ACConsoleApp
{
    class Program
    {
        public static int[] RemoveDuplicates(int[] input)
        {
            HashSet<int> hashSet = new HashSet<int>(input);
            int[] result = new int[hashSet.Count];
            hashSet.CopyTo(result);
            return result;
        }
        static void Main(string[] args)
        {
            int[] inputArray = new[] {1, 5, 2, 6, 1, 4, 2};
            var result = RemoveDuplicates(inputArray);
            for(int i=0 ;i<result.Length;i++)
            {
                Console.WriteLine(result[i]);
            }
            Console.ReadLine();
        }
    }
}

Leave Your Comment