Pan*_*cus 6 .net c# string collections optimization
如果我存储了一堆字符串值并且我希望能够在O(1)之后找到它们,我经常做的事情是:
foreach (String value in someStringCollection)
{
someDictionary.Add(value, String.Empty);
}
Run Code Online (Sandbox Code Playgroud)
这样,我可以在以后轻松地对这些字符串值执行常量时间查找,例如:
if (someDictionary.containsKey(someKey))
{
// etc
}
Run Code Online (Sandbox Code Playgroud)
但是,我觉得我在制作值String.Empty时作弊.我应该使用更合适的.NET Collection吗?
如果您使用的是.Net 3.5,请尝试使用HashSet.如果您不使用.Net 3.5,请尝试使用C5.否则你当前的方法是可以的(bool,因为@leppie建议更好,或者不像@JonSkeet建议的那样,dun dun dun!).
HashSet<string> stringSet = new HashSet<string>(someStringCollection);
if (stringSet.Contains(someString))
{
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
461 次 |
| 最近记录: |