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?
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;
}
}
}
Don't use a dictionary if the order of the values are important. The things that come off the top of my head are a SortedDictionary or a List<KeyValuePair>
.
If you are okay to sort it based on the key then a SortedDictionary may suit you. AFAIK there is no generic implementation of OrderedDictionary unless you implement one.
I had to rewrite David Yaw's TryGetValue from his excellent suggestion since 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;
}
精彩评论