Getting distinct values from arrays

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace ConsoleApplication2

{

    class Program

    {

        static void Main(string[] args)

        {

            int[] integerArray = { 1, 2, 3, 4, 5, 1, 2, 3, 4, 5 };

            for (int i = 0; i < integerArray.Length; i++)

            {

                if (i < integerArray.Length – 1)

                {

                    Console.Write(integerArray[i] + ", ");

                }

                else

                {

                    Console.Write(integerArray[i]);

                }

            }

            Console.WriteLine();

            Console.WriteLine("Printing distinct elements:");

            int[] newIntegerArray = integerArray.Distinct().ToArray();

            for (int i = 0; i < newIntegerArray.Length; i++)

            {

                if (i < newIntegerArray.Length – 1)

                {

                    Console.Write(newIntegerArray[i] + ", ");

                }

                else

                {

                    Console.Write(newIntegerArray[i]);

                }

            }

            Console.WriteLine();

            Console.WriteLine("Printing distinct elements:");

            newIntegerArray = GetDistinctValues(integerArray);

            for (int i = 0; i < newIntegerArray.Length; i++)

            {

                if (i < newIntegerArray.Length – 1)

                {

                    Console.Write(newIntegerArray[i] + ", ");

                }

                else

                {

                    Console.Write(newIntegerArray[i]);

                }

            }

            Console.WriteLine();

        }

        public static int[] GetDistinctValues(int[] array)

        {

            List<int> list = new List<int>();

            for (int i = 0; i < array.Length; i++)

            {

                if (list.Contains(array[i]))           

                    continue;

                list.Add(array[i]);

            }

            return list.ToArray();

        }

    }

}

http://weblogs.asp.net/gunnarpeipman/archive/2008/05/15/getting-distinct-values-from-arrays.aspx

Advertisements
This entry was posted in Information Technology. Bookmark the permalink.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s