Count distinct elements in an array | C # Program to count Unique elements in Array ; This function prints all distinct elements ; Creates an empty hashset ; Traverse the input array ; If not present , then put it in hashtable and increment result ; Driver code
using System ; using System . Collections . Generic ; class GFG { public static int countDistinct ( int [ ] arr , int n ) { HashSet < int > hs = new HashSet < int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { hs . Add ( arr [ i ] ) ; } return hs . Count ; } public static void Main ( ) { int [ ] arr = new int [ ] { 6 , 10 , 5 , 4 , 9 , 120 , 4 , 6 , 10 } ; Console . WriteLine ( countDistinct ( arr , arr . Length ) ) ; } }