.NET SortedDictionary But Sorted By Values

喜欢而已 提交于 2020-01-20 08:10:12

问题


I need a data structure that acts like a SortedDictionary<int, double> but is sorted based on the values rather than the keys. I need it to take about 1-2 microseconds to add and remove items when we have about 3000 items in the dictionary.

My first thought was simply to switch the keys and values in my code. This very nearly works. I can add and remove elements in about 1.2 microseconds in my testing by doing this.

But the keys have to be unique in a SortedDictionary so that means that values in my inverse dictionary would have to be unique. And there are some cases where they may not be.

Any ideas of something in the .NET libraries already that would work for me?


回答1:


The PowerCollections library has a class called OrderedMultiDictionary<TKey, TValue> that is basically like a SortedDictionary<TKey, TValue> but allows duplicates. When you lookup a key, you get an enumerable instead of a single value.

The library is free and you should be able to do exactly what you want with that class - store the values as the keys.




回答2:


You can sort SortedDictionary by value like this:

yourList.Sort(
    delegate(KeyValuePair<int, double> val1,
    KeyValuePair<int, double> val2)
    {
        return val1.Value.CompareTo(val2.Value);
    }
);


来源:https://stackoverflow.com/questions/2619051/net-sorteddictionary-but-sorted-by-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!