“适当的”集合用于获取项目在O(1)时间在C#.NET? [英] 'Proper' collection to use to obtain items in O(1) time in C# .NET?

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

问题描述

我经常如果我存储一串字符串值,我想能够在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, href =http://msdn.microsoft.com/en-us/library/bb359438.aspx =nofollow noreferrer> HashSet 。如果您不使用.Net 3.5,请尝试 C5 。否则你的当前方法是确定的(bool as @leppie建议是更好,或不像@JonSkeet建议,dun dun dun!)。

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))
{
    ...
}

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

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