C#:如果数组不包含字符串,则将字符串添加到数组中

Rof*_*ion 2 c#

我有很多字符串数组.从所有这些字符串数组中,我想创建一个唯一字符串数组.目前我这样做:

string[] strings = {};

while(running)
{
   newStringArrayToAdd[] = GetStrings();
   strings = strings.Concat(newStringArrayToAdd).ToArray();
}

uniqueStrings = strings.Distinct.ToArray();
Run Code Online (Sandbox Code Playgroud)

这是有效的,但它非常慢,因为我必须将字符串变量保持在内存中,这变得非常巨大.因此,如果字符串在uniqueStrings中,如果不立即添加,我正在寻找一种方法来检查.我怎样才能做到这一点?

p.s*_*w.g 11

考虑使用a HashSet<string>而不是数组.如果字符串已经存在于集合中,它将不执行任何操作:

HashSet<string> strings = new HashSet<string>();

strings.Add("foo");
strings.Add("foo");

strings.Count // 1
Run Code Online (Sandbox Code Playgroud)

UnionWith方法在您的示例代码中非常有用:

HashSet<string> strings = new HashSet<string>();

while(running)
{
   string[] newStringArrayToAdd = GetStrings();
   strings.UnionWith(newStringArrayToAdd);
}
Run Code Online (Sandbox Code Playgroud)