.NET中键/值对位置的随机访问(C#)

时间:2009-07-02 22:47:32

标签: c# .net .net-2.0 dictionary

我目前正在开发一个使用C#的Dictionary容器(特别是SortedDictionary)的程序。这个容器非常适合我的目的,除了一个特定的情况,因为我想随机访问。具体来说,我使用伪随机数生成器生成随机位置,我需要能够在SortedDictionary中访问该值。在发生这种情况时,我没有密钥值。

我可能会切换到一个可以解决这个问题的List,但会在SortedDictionary运行良好的算法的其余部分产生问题。任何建议/解决方案都将非常感激。

我目前正在开发Visual Studio 2005。

谢谢。

5 个答案:

答案 0 :(得分:4)

您可以使用SortedList,它有一个可以通过整数索引访问的Values集合。

答案 1 :(得分:2)

    public TValue GetRandomElement<TKey, TValue>(SortedDictionary<TKey, TValue> dict)
    {
        Random randGen = new Random();
        int randIndex = randGen.Next(dict.Values.Count);
        int i = 0;
        foreach (TValue value in dict.Values)
        {
            if (i++ == randIndex)
                return value;
        }

        // this shouldn't happen unless I have a bug above or you are accessing the dictionary from multiple threads
        return default(TValue);
    }

盲目地枚举ValueCollection并不是世界上最有效的事情。但它完成了工作。如果这是您的方案中的常见操作,则应考虑具有字典查找和随机访问所需的性能特征的混合数据结构。

答案 2 :(得分:1)

Linq可以为你做这件事:

int n = GetRandomIndex();
object item = dictionary.ElementAt(n).Value;

答案 3 :(得分:0)

拉随机密钥工作吗?

var randValue = myDictionary.Values.ToList()[myRandomInt];

修改

似乎密钥集合和值集合都是IEnumerables,所以你不能使用[]运算符。这是它看起来最好的。

修改

没有Linq ......也许很贵,但你可以复制到数组,然后在索引处拉一个值

System.Collections.Generic.KeyValuePair<string, int>[] dictCopy = new System.Collections.Generic.KeyValuePair<string, int>[myDictionary.Count];
myDictionary.CopyTo(dictCopy, 0);
var randValue = dictCopy[myRandomInt].Value;

答案 4 :(得分:0)

您没有提供足够的信息来提出解决方案。有多少元素,你经常这样做,你有内存/速度限制吗? BTree,SortedList,在SortedDictionary中插入特殊节点都可能有用