如何从C#中的集合中获取唯一值?

Geo*_*ge2 3 .net c# visual-studio-2008

我使用的是C#+ VSTS2008 + .Net 3.0.我有一个输入作为字符串数组.我需要输出数组的唯一字符串.任何想法如何有效地实现这一点?

例如,我输入{"abc","abcd","abcd"},我想要的输出是{"abc","abcd"}.

Phi*_*ert 19

使用LINQ:

var uniquevalues = list.Distinct();
Run Code Online (Sandbox Code Playgroud)

这给了你一个IEnumerable<string>.

如果你想要一个数组:

string[] uniquevalues = list.Distinct().ToArray();
Run Code Online (Sandbox Code Playgroud)

如果您不使用.NET 3.5,则会更复杂一些:

List<string> newList = new List<string>();

foreach (string s in list)
{
   if (!newList.Contains(s))
      newList.Add(s);
}

// newList contains the unique values
Run Code Online (Sandbox Code Playgroud)

另一个解决方案(可能更快一点):

Dictionary<string,bool> dic = new Dictionary<string,bool>();

foreach (string s in list)
{
   dic[s] = true;
}

List<string> newList = new List<string>(dic.Keys);

// newList contains the unique values
Run Code Online (Sandbox Code Playgroud)


Kob*_*obi 9

另一种选择是使用HashSet:

HashSet<string> hash = new HashSet<string>(inputStrings);
Run Code Online (Sandbox Code Playgroud)

我想我也会选择linq,但这也是一个选择.

编辑:
您已将问题更新为3.0,这可能会有所帮助: 在C#2.0中使用HashSet,与3.5兼容