How do I remove duplicates from a C# array?

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?


您可以使用LINQ查询来执行此操作:

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.


If you needed to sort it, then you could implement a sort that also removes duplicates.

Kills two birds with one stone, then.

链接地址: http://www.djcxy.com/p/51320.html

上一篇: 如何使用LINQ从DataTable中获得独特的有序名称列表?

下一篇: 如何从C#数组中删除重复项?