Find Distinct Values in C# Array

 

In this article we discuss about how to find number of distinct values in a given array and what are those distinct values by using two methods. We can find distinct values from array by using LINQ or without using LINQ also, we discuss both approaches.

 

Using LINQ

 

Through LINQ we can use Distinct() method to find the distinct values from an array as shown below.

 

using System;

using System.Linq;

 

namespace DistinctArray

{

    class Program

    {

        static void Main(string[] args)

        {

            int[] arry = new int[10]{1,2,3,4,4,5,6,7,8,8};

 

            Console.WriteLine("The Array Length : {0} & Number Of Distinct Values : {1}",arry.Length, GetDistinctArray(arry));

            Console.ReadLine();

        }

 

        static int GetDistinctArray(int[] myArray)

        {

            int numberOfDistElements = myArray.Distinct().Count();

            return numberOfDistElements;

        }

    }

}

 

Run the above program, the output is as shown below.

 

 

 

Using Non-LINQ Method

 

If you are working on .Net 2.0 or previous versions, we don't have LINQ so we have to write our own custom code as shown below to find the distinct values.

 

using System;

using System.Linq;

using System.Collections.Generic;


namespace DistinctArray

{

    class Program

    {

        static void Main(string[] args)

        {

            int[] arry = new int[10] { 1, 2, 3, 4, 4, 5, 6, 7, 8, 8 };

 

            Console.WriteLine("The Array Length : {0} & Number Of Distinct Values : {1}", arry.Length, GetDistinctArray(arry));

            Console.ReadLine();

        }

 

        static int GetDistinctArray(int[] myArray)

        {

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

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

            {

                if (!list.Contains(myArray[i]))

                    list.Add(myArray[i]);

            }

            int numberOfDistElements = list.Count;

 

            return numberOfDistElements;

        }

    }

}

 

As shown above we have generic list  list, looping through each element in array and check whether that element is there in list or not. If element is not there in list, add to it otherwise ignore it. By using Count property of list we can find the number of elements in list.

 

Run the program and the output is as shown below.