C # Inverse elements in a dictionary

I am trying to swap elements in a dictionary in C #. I tried:

Dictionary<double, int> dict = new Dictionary<double, int>();
...add itmes to it....
var v = dict.Reverse()

However, dict.Reverse () gives me an IEnumberable> type. I'm just wondering how can I do this with the Dictionary?

Thanks in advance.

+3
source share
3 answers

A dictionary is not an ordered data structure. For Reverse to make any real sense, you need to use SortedDictionary. You can get a reverse copy of SortedDictionary by creating a new one using Comparer, which does the opposite sort with the original (see constructor ).

var reversed = new SortedDictionary( original, new ReverseKeyComparer() );

Note that ReverseKeyComparerthis is a dummy class for example.

, , SortedDictionary , -. (Red-Black, ) , - . . "" . , , .

+11

!

- .

.

+16

If you want the dictionaries to have a specific order, you should look in the SortedDictionary. See this article.

+3
source

Source: https://habr.com/ru/post/1756916/


All Articles