目前我有包含两个字符串的对象:
class myClass
{
public string string1 { get; set; }
public string string2 { get; set; }
public bool MatcheString1(string newString)
{
if (this.string1 == newString)
{
return true;
}
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
然后,我有一个第二个类,使用List列出上述对象.
class URLs : IEnumerator, IEnumerable
{
private List<myClass> myCustomList;
private int position = -1;
// Constructor
public URLs()
{
myCustomList = new List<myClass>();
}
}
Run Code Online (Sandbox Code Playgroud)
在那个类中,我正在使用一种方法来检查列表中是否存在字符串
// We can also check if the URL string is present in the collection
public bool ContainsString1(string newString)
{
foreach (myClass entry in myCustomList)
{
if (entry. MatcheString1(newString))
{
return true;
}
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
基本上,随着对象列表增长到100,000标记,此过程变得非常缓慢.什么是检查该字符串是否存在的快速方法?我很高兴在类之外创建一个List进行验证,但这对我来说似乎很烦人?
一旦项目列表稳定,您就可以计算匹配的哈希集,例如:
// up-front work
var knownStrings = new HashSet<string>();
foreach(var item in myCustomList) knownStrings.Add(item.string1);
Run Code Online (Sandbox Code Playgroud)
(请注意,这不是免费的,并且需要在列表更改时重新计算); 那么,以后,你可以检查:
return knownStrings.Contains(newString);
Run Code Online (Sandbox Code Playgroud)
然后非常便宜(O(1)而不是O(N)).