How do I remove duplicates from a C# array?


Question

I have been working with a string[] array in C# that gets returned from a function call. I could possibly cast to a Generic collection, but I was wondering if there was a better way to do it, possibly by using a temp array.

What is the best way to remove duplicates from a C# array?

1
197
9/26/2017 7:21:51 PM

Accepted Answer

You could possibly use a LINQ query to do this:

int[] s = { 1, 2, 3, 3, 4};
int[] q = s.Distinct().ToArray();
408
8/13/2008 12:03:05 PM

Here is the HashSet<string> approach:

public static string[] RemoveDuplicates(string[] s)
{
    HashSet<string> set = new HashSet<string>(s);
    string[] result = new string[set.Count];
    set.CopyTo(result);
    return result;
}

Unfortunately this solution also requires .NET framework 3.5 or later as HashSet was not added until that version. You could also use array.Distinct(), which is a feature of LINQ.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon