How to Remove Duplicates from an Array in C#

If you’ve ever worked with arrays in C#, you’ve probably encountered the issue of eliminating duplicate data. There is no built-in function in C# for removing duplicates from an array. You can achieve the same objective, though, by creating a new array with different values. In this post, we will look at How to Remove Duplicates from an Array in c#.

Remove Duplicate Element in Array C#

As previously indicated, C# doesn’t have a built-in function for removing duplicate values from an array. We can instead build a new array with separate values. Getting unique values refers to the process of constructing a new array containing separate values.

The following example uses the Distinct() function to extract distinct values from an array and then builds a new array.

Remove Duplicate in an integer array

  public static int[] removeduplicatearray()
        {
            int[] arraynum = { 2, 5, 4, 3, 2, 7 };
            int[] distinctarray = arraynum.Distinct().ToArray();

            return distinctarray;
        }

We have an integer array arraynum with six members in the above code, and we want to delete the duplicates. We use the Distinct() function to create a new array that only contains the original array’s distinct members. Finally, we transform the output into an array and assign it to the original array.

Remove Duplicate in a string array

  public static string[] removeduplicatearraystring()
        {
            string[] arraystr = { "Apple", "Samsung", "Honor", "Redmi", "Apple" };
            string[] distinctarraystring = arraystr.Distinct().ToArray();

            return distinctarraystring;
        }

Try it

We have an integer array arraystr with five members in the above code, and we want to delete the duplicates. We use the Distinct() function to create a new array that only contains the original array’s distinct members. Finally, we transform the output into an array and assign it to the original array.

More Related Post: Remove Elements from an Array in C#

Conclusion

In this article, we explored How to Remove Duplicates from an Array in c#. We learned that we can achieve the same result by creating a new array with distinct values

Leave a Reply

Your email address will not be published. Required fields are marked *