Coder Perfect

How do I remove duplicates from a C# array?

Problem

In C#, I’ve been working with a string[] array returned by a function call. I suppose I could cast to a Generic collection, but I’m wondering if there’s a better solution, such as utilizing a temp array.

How can I remove duplicates from a C# array in the most efficient way?

Asked by lomaxx

Solution #1

You might be able to accomplish this using a LINQ query:

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

Answered by Jeff Atwood

Solution #2

The HashSetstring> method is as follows:

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, because HashSet was not added until that version, this solution also requires.NET framework 3.5 or later. You might alternatively make use of an array. Distinct(), which is a LINQ functionality.

Answered by Arcturus

Solution #3

The tested and functional code below will eliminate duplicates from an array. The namespace System.Collections must be included.

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]);
}

If you wanted to, you could turn this into a function.

Answered by GateKiller

Solution #4

You might use a sort that also removes duplicates if you needed to sort it.

Then he kills two birds with a single stone.

Answered by Matthew Schinckel

Solution #5

This may depend on how much you want to engineer the answer; for example, if the array will never be that large and you don’t care about sorting the list, you may attempt something like this:

    public string[] RemoveDuplicates(string[] myList) {
        System.Collections.ArrayList newList = new System.Collections.ArrayList();

        foreach (string str in myList)
            if (!newList.Contains(str))
                newList.Add(str);
        return (string[])newList.ToArray(typeof(string));
    }

Answered by rjzii

Post is based on https://stackoverflow.com/questions/9673/how-do-i-remove-duplicates-from-a-c-sharp-array