在C#中从字符串数组中高效地删除重复字符串的方法

8
我希望您能够提供一种高效的方法,在C#中从字符串数组中删除重复项。例如,
string[] a = { "abc", "xyz","abc", "def", "ghi", "asdf", "ghi","xd", "abc" };

将变成:
string[] a = { "abc", "xyz","def", "ghi", "asdf", "xd" };

如何在删除重复项后填补空缺?有没有一种方法可以不使用额外的数组来存储元素?
我使用的方法:
1) Sorted the array

2) Replaced the duplicate entries with null

3) Copied NOT null string to a new array.

但是我正在寻找一种优化的方法来完成同样的任务。
编辑:我正在使用.NET 2.0和VS 2005。
4个回答

16

你可以使用 HashSet:

string[] a = { "abc", "xyz","abc", "def", "ghi", "asdf", "ghi","xd", "abc" };
var b = new HashSet<string>(a);

我能在使用 .Net 2.0 的 VS 2005 中使用 var 吗? - SyncMaster

10

在.NET中,你无法调整数组的大小,因此无论你使用什么方式来删除重复项,都必须为结果创建一个新的数组。

你可以使用HashSet<string>轻松地去除重复项:

a = new HashSet<string>(a).ToArray();

哈希集合将数组中的项目添加到自身,并自动丢弃重复项。由于哈希集合使用哈希码来检查现有项,因此这比对项目进行排序要快一些,但结果当然不是排序的。


我安装了 .Net 3.5 更新。但是我收到了错误信息:“'System.Collections.Generic.HashSet<string>' 不包含 'ToArray' 的定义”。 - SyncMaster
@pragadheesh:ToArray不是类本身的方法,而是扩展方法。您需要在文件顶部使用using System.Linq;来获取扩展方法。 - Guffa


6

如果使用 .NET 3.0,您可以使用LINQ:

using System;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] a = { "abc", "xyz", "abc", "def", "ghi", "asdf", "ghi", "xd", "abc" };
            string[] b = a.Distinct().ToArray();
            foreach (string s in b)
                Console.WriteLine(s);
            Console.ReadLine();
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接