remove duplicates from string array in csharp

You can remove duplicates from a string array in C# by using the Distinct() method of LINQ. Here's how you can do it:

main.cs
string[] arr = {"apple", "banana", "orange", "banana", "grape", "apple"};
string[] distinctArr = arr.Distinct().ToArray();
123 chars
3 lines

In this example, the arr array contains duplicate values, namely "apple" and "banana". The Distinct() method removes these duplicates, and the resulting distinctArr array contains the unique values from arr, in the order they appeared in the original array.

If you don't want to preserve the order of the elements, you can use the OrderBy() method before calling Distinct():

main.cs
string[] arr = {"apple", "banana", "orange", "banana", "grape", "apple"};
string[] distinctArr = arr.OrderBy(x => x).Distinct().ToArray();
139 chars
3 lines

In this modified example, the OrderBy() method orders the elements in arr alphabetically before calling Distinct(). The resulting distinctArr array contains the unique values from arr, sorted alphabetically.

gistlibby LogSnag