How do I remove duplicates from a C# array? How do I remove duplicates from a C# array? arrays arrays

How do I remove duplicates from a C# array?


You could possibly use a LINQ query to do this:

int[] s = { 1, 2, 3, 3, 4};int[] q = s.Distinct().ToArray();


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.


The following tested and working code will remove duplicates from an array. You must include the System.Collections namespace.

string[] sArray = {"a", "b", "b", "c", "c", "d", "e", "f", "f"};var sList = new ArrayList();for (int i = 0; i < sArray.Length; i++) {    if (sList.Contains(sArray[i]) == false) {        sList.Add(sArray[i]);    }}var sNew = sList.ToArray();for (int i = 0; i < sNew.Length; i++) {    Console.Write(sNew[i]);}

You could wrap this up into a function if you wanted to.