How to remove duplicate values from an array in C#?

0

 

How to remove duplicate values from an array in C#?


In C# programming, it is common to work with arrays that contain duplicate values. Removing duplicate values from an array can help optimize your code and improve performance. In this blog post, we will show you how to remove duplicate values from an array in C# using two different methods.

Method 1: Using LINQ Distinct() Method

The easiest and most straightforward way to remove duplicate values from an array in C# is to use the Distinct() method provided by the Language-Integrated Query (LINQ) library. This method returns a new array that contains only the unique elements from the original array.

Here is an example of how to use the Distinct() method:


int[] numbers = { 1, 2, 3, 3, 4, 5, 5, 6 };
int[] distinctNumbers = numbers.Distinct().ToArray();

In this example, the Distinct() method is applied to the numbers array, and the resulting array, distinctNumbers, contains only the unique elements from the original array.


Method 2: Using a HashSet :

Another way to remove duplicate values from an array in C# is to use a HashSet. A HashSet is a collection that contains unique elements, and it can be used to remove duplicates from an array.

Here is an example of how to use a HashSet:


int[] numbers = { 1, 2, 3, 3, 4, 5, 5, 6 };
HashSet<int> uniqueNumbers = new HashSet<int>(numbers);
int[] distinctNumbers = uniqueNumbers.ToArray();

In this example, a HashSet is created using the numbers array, and then the HashSet is converted back to an array using the ToArray() method. The resulting array, distinctNumbers, contains only the unique elements from the original array.

Removing duplicate values from an array in C# is a common task in programming. In this blog post, we have shown you two different methods for removing duplicates from an array: using the Distinct() method provided by LINQ, and using a HashSet. Both methods are simple and efficient, and you can choose the one that best suits your needs. By using these methods, you can easily remove duplicate values from any C# array and optimize your code.


Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !