Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a type-safe ordered dictionary alternative? [duplicate]

Tags:

c#

dictionary

I want to save some pairs in a dictionary.

At the end I want to serialize the dictionary to a JSON object. I then print the JSON content. I want the pairs to be printed in the same order they were entered in the dictionary.

At first I used an ordinary dictionary. But then I thought the order might not be kept. Then I migrated to OrderedDictionary, but it doesn't use Generic, meaning it's not type-safe.

Do you have any other good-practice solution for me?

like image 631
Elad Benda Avatar asked Dec 28 '22 23:12

Elad Benda


1 Answers

If you can't find a replacement, and you don't want to change the collection type you're using, the simplest thing may be to write a type-safe wrapper around OrderedDictionary.

It is doing the same work you're doing now, but the un-type-safe code is much more limited, just in this one class. In this class, we can rely on the backing dictionary only having TKey and TValue types in it, because it could only have been inserted from our own Add methods. In the rest of your application, you can treat 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;
        }
    }
}
like image 169
David Yaw Avatar answered Dec 30 '22 12:12

David Yaw