Is there an alternative version of the standard dictionary?

I want to save several pairs in the dictionary.

In the end, I want to serialize the dictionary into a JSON object. Then I print the contents of the JSON. I want the pairs to be printed in the same order in which they were entered in the dictionary.

At first I used a regular dictionary. But then I thought that the order would not be respected. Then I switched to OrderedDictionary, but it does not use Generic, that is, it is not type-safe.

Do you have any other solution for me?

+4
source share
4 answers

Do not use a dictionary if the order of values ​​is important. What comes off my head is SortedDictionary or List<KeyValuePair> .

+1
source

If you cannot find a replacement, and you do not want to change the type of collection you are using, the simplest way is to create a protected wrapper type around the OrderedDictionary.

It does the same thing you are doing now, but code that does not match the type is much more limited, only in this class. In this class, we can rely on a support dictionary that contains only the TKey and TValue types, because it can only be inserted from our own Add methods. In the rest of the application, you can see this as a type-safe collection.

 public class OrderedDictionary<TKey, TValue> : IDictionary<TKey, TValue> { private OrderedDictionary backing = new OrderedDictionary(); // for each IDictionary<TKey, TValue> method, simply call that method in // OrderedDictionary, performing the casts manually. Also duplicate any of // the index-based methods from OrderedDictionary that you need. void Add(TKey key, TValue value) { this.backing.Add(key, value); } bool TryGetValue(TKey key, out TValue value) { object objValue; bool result = this.backing.TryGetValue(key, out objValue); value = (TValue)objValue; return result; } TValue this[TKey key] { get { return (TValue)this.backing[key]; } set { this.backing[key] = value; } } } 
+6
source

If you can sort it by key, then SortedDictionary may suit you . AFAIK there is no universal implementation of OrderedDictionary, unless you implement it.

+1
source

I had to rewrite David Yaw's TryGetValue from his excellent suggestion, because OrderedDictionary does not have a TryGetValue method. Here is my modification.

  bool TryGetValue(TKey key, out TValue value) { object objValue; value = default(TValue); try { objValue = this.backing[key]; value = (TValue)objValue; } catch { return false; } return true; } 
0
source

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


All Articles