c# – 如果字符串存在于大型对象列表中,那么比较最快(性能)的方
发布时间:2020-12-16 01:58:07 所属栏目:百科 来源:网络整理
导读:目前我有包含两个字符串的对象: 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; }} 然后,我有
目前我有包含两个字符串的对象:
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; } } 然后,我有一个第二个类,使用List列出上述对象. class URLs : IEnumerator,IEnumerable { private List<myClass> myCustomList; private int position = -1; // Constructor public URLs() { myCustomList = new List<myClass>(); } } 在那个类中,我正在使用一种方法来检查列表中是否存在字符串 // 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; } 基本上,随着对象列表增长到100,000标记,此过程变得非常缓慢.什么是检查该字符串是否存在的快速方法?我很高兴在类之外创建一个List进行验证,但这对我来说似乎很烦人? 解决方法
一旦项目列表稳定,您就可以计算匹配的哈希集,例如:
// up-front work var knownStrings = new HashSet<string>(); foreach(var item in myCustomList) knownStrings.Add(item.string1); (请注意,这不是免费的,并且需要在列表更改时重新计算);然后,你可以检查一下: return knownStrings.Contains(newString); 然后非常便宜(O(1)而不是O(N)). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |