Home >Backend Development >C++ >Why Is There No Generic OrderedDictionary in .NET 3.5, and How Can I Implement One?
.NET 3.5 doesn't provide a generic implementation of OrderedDictionary (from the System.Collections.Specialized namespace).
There are known implementations that can provide this functionality, but it's unclear why this implementation isn't included out-of-the-box and whether it will be included in .NET 4.0.
Implementing a generic OrderedDictionary isn't complex, but can be time-consuming. Here's a solution using a KeyedCollection for internal storage:
public interface IOrderedDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IOrderedDictionary { new TValue this[int index] { get; set; } new TValue this[TKey key] { get; set; } new int Count { get; } new ICollection<TKey> Keys { get; } new ICollection<TValue> Values { get; } new void Add(TKey key, TValue value); new void Clear(); void Insert(int index, TKey key, TValue value); int IndexOf(TKey key); bool ContainsValue(TValue value); bool ContainsValue(TValue value, IEqualityComparer<TValue> comparer); new bool ContainsKey(TKey key); new IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator(); new bool Remove(TKey key); new void RemoveAt(int index); new bool TryGetValue(TKey key, out TValue value); TValue GetValue(TKey key); void SetValue(TKey key, TValue value); KeyValuePair<TKey, TValue> GetItem(int index); void SetItem(int index, TValue value); }
public class OrderedDictionary<TKey, TValue> : IOrderedDictionary<TKey, TValue> { private KeyedCollection2<TKey, KeyValuePair<TKey, TValue>> _keyedCollection; public TValue this[TKey key] { get { return GetValue(key); } set { SetValue(key, value); } } public TValue this[int index] { get { return GetItem(index).Value; } set { SetItem(index, value); } }
The above is the detailed content of Why Is There No Generic OrderedDictionary in .NET 3.5, and How Can I Implement One?. For more information, please follow other related articles on the PHP Chinese website!