.NET 中按键/值对位置随机访问 (C#)
我目前正在开发一个使用 C# 的 Dictionary 容器(具体来说,SortedDictionary)的程序。 这个容器非常适合我的目的,除了一种特定情况,因为我想要随机访问。 具体来说,我使用伪随机数生成器生成随机位置,并且我需要能够访问 SortedDictionary 中的该值。 当这种情况发生时,我没有关键值。
我可能会切换到列表来解决这个问题,但会在 SortedDictionary 工作得很好的算法的其余部分中产生问题。 任何建议/解决方案将不胜感激。
我目前正在开发 Visual Studio 2005。
谢谢。
I am currently developing a program that uses C#'s Dictionary container (specifically, SortedDictionary). This container works very well for my purposes except for one specific case because I want random access. Specifically, I am generating a random position using a pseudorandom number generator and I need to be able to access that value in the SortedDictionary. At the point that this happens, I do not have a key value.
I could potentially switch to a List which would solve this problem, but would create problems in the rest of the algorithm where SortedDictionary works quite well. Any suggestions/solutions would be much appreciated.
I am currently developing Visual Studio 2005.
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用 SortedList,它有一个 Values 集合,您可以通过整数索引访问该集合。
You can use a SortedList and it has a Values collection which you may access through an integer index.
盲目枚举 ValueCollection 并不是世界上最有效的事情。 但它完成了工作。 如果这是您的场景中的频繁操作,您应该考虑具有字典查找和随机访问所需的性能特征的混合数据结构。
Blindly enumerating the ValueCollection is not the most efficient thing in the world. But it gets the job done. If this is a frequent operation in your scenario, you should consider a hybrid data structure that has the performance characteristics needed for both dictionary lookup and random access.
Linq 可以为你做到这一点:
Linq could do this for you:
您没有提供足够的信息来提出解决方案。 有多少个元素,您打算多久执行一次此操作,您是否有内存/速度限制? BTree、SortedList、在 SortedDictionary 中插入特殊节点都可能有用
You don't provide enough information to come up with a solution. How many elements, how often are you going to do this, do you have memory/speed constraints? BTree, SortedList, inserting special nodes in the SortedDictionary could all be useful
提取随机密钥有效吗?
编辑:
似乎键集合和值集合都是 IEnumerables,因此您不能使用 [] 运算符。 这似乎是最好的。
编辑:
没有 Linq...也许很昂贵,但您可以复制到数组,然后在索引处提取值
Will pulling a random key work?
Edit:
Seems the keys collection and values collection are both IEnumerables so you can't use [] operators. This is the best it gets it seems.
Edit:
Without Linq... Perhaps expensive, but you could copyto array and then pull a value at an index