Removing duplicate values from an array is a common task in C# programming. There are several methods to remove duplicates from an array, but in this blog, we'll discuss two of the most efficient methods.
Method 1: Using HashSet :
One of the easiest and most efficient ways to remove duplicates from an array is by using a HashSet
. A HashSet
is a collection type in C# that does not allow duplicate values. When you add values to a HashSet
, it automatically removes any duplicates.
Here's an example that demonstrates how to remove duplicates from an array using a HashSet
in C#:
In this example, we created an array of integers named numbers
and assigned some values to it.
Next, we created a HashSet
named uniqueNumbers
and initialized it with the numbers
array. The HashSet
constructor automatically removes any duplicates and stores only unique values.
Finally, we used the Console.WriteLine
method to print the original array and the uniqueNumbers
on the console. The output of the program will show the original array and the uniqueNumbers
with no duplicates.
Method 2: Using LINQ :
Another method to remove duplicates from an array is by using LINQ (Language Integrated Query). LINQ provides several extension methods to perform various operations on arrays, including removing duplicates.
Here's an example that demonstrates how to remove duplicates from an array using LINQ in C#:
In this example, we created an array of integers named numbers
and assigned some values to it.
Next, we used the Distinct
method from LINQ to remove duplicates from the numbers
array. The Distinct
method returns a new array that contains only unique values from the original array.
Finally, we used the ToArray
method to convert the result of the Distinct
method into an array, and we stored it in the uniqueNumbers
array.
Finally, we used the Console.WriteLine
method to print the original array and the uniqueNumbers
on the console. The output of the program will show the original array and the uniqueNumbers
with no duplicates.
The above code demonstrates the two methods of removing duplicates from an array in C#. Whether you choose the HashSet
method or the LINQ method, both methods provide an efficient way to remove duplicates from an array.
In conclusion, it's important to understand how to remove duplicates from an array as it is a common task in programming. With the help of the HashSet
or LINQ, you can easily remove duplicates from an array and get the desired output. So, make sure to practice these methods and add them to your toolkit as a C# programmer.