“正确的”集合使用,以获得在C#.NET在O(1)时间的项目? [英] 'Proper' collection to use to obtain items in O(1) time in C# .NET?

查看:126
本文介绍了“正确的”集合使用,以获得在C#.NET在O(1)时间的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做的事情的时候,如果我存储一串字符串值,我希望能够找到它们在O(1)时间晚:

Something I do often if I'm storing a bunch of string values and I want to be able to find them in O(1) time later is:

foreach (String value in someStringCollection)
{
    someDictionary.Add(value, String.Empty);
}

这样的话,我可以轻松地执行固定时间这些字符串值查找以后,如:

This way, I can comfortably perform constant-time lookups on these string values later on, such as:

if (someDictionary.containsKey(someKey))
{
    // etc
}

不过,我觉得我是通过使值的String.Empty 作弊。有没有更合适的.NET集合,我应该使用?

However, I feel like I'm cheating by making the value String.Empty. Is there a more appropriate .NET Collection I should be using?

推荐答案

如果您正在使用.net 3.5,尝试的 HashSet的。如果你不使用.net 3.5,尝试 C5 。否则,当前的方法是确定(布尔作为@leppie建议比较好,还是不作为@JonSkeet表明,顿顿讨债!)。

If you're using .Net 3.5, try HashSet. If you're not using .Net 3.5, try C5. Otherwise your current method is ok (bool as @leppie suggests is better, or not as @JonSkeet suggests, dun dun dun!).

HashSet<string> stringSet = new HashSet<string>(someStringCollection);

if (stringSet.Contains(someString))
{
    ...
}

这篇关于“正确的”集合使用,以获得在C#.NET在O(1)时间的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆