Remove Duplicate Array Entries Using Distinct() Method

You can use the IEnumerable.Distinct method on an array to get all of the elements of the array, with the duplicates removed.
This method returns a result of the type IEnumerable<T>, where is the type of the element in the array.  You can iterate through this new list using the foreach statement, or count the number of elements using the Count method.


1
2
3
4
5
6
7
8
int[] scores = { 88, 99, 79, 88, 78, 100, 79 };
 
// # of unique scores
Console.WriteLine("# unique = {0}", scores.Distinct().Count());   // 5
 
// List only the unique scores
foreach (int next in scores.Distinct())
    Console.WriteLine("Score : {0}", next);