#152 – 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 T 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.

            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);
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: