Implementing a Generic OrderedDictionary
While a generic implementation of OrderedDictionary may not be available in .NET 3.5, creating one isn't overly complex. We can leverage a KeyedCollection for storage and implement various methods to sort items like List
Interface
public interface IOrderedDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IOrderedDictionary { // ... }
Implementation
public class OrderedDictionary<TKey, TValue> : IOrderedDictionary<TKey, TValue> { private KeyedCollection2<TKey, KeyValuePair<TKey, TValue>> _keyedCollection; // ... }
Helper Classes
public class KeyedCollection2<TKey, TItem> : KeyedCollection<TKey, TItem> { private Func<TItem, TKey> _getKeyForItemDelegate; // ... } public class Comparer2<T> : Comparer<T> { private readonly Comparison<T> _compareFunction; // ... } public class DictionaryEnumerator<TKey, TValue> : IDictionaryEnumerator, IDisposable { // ... }
Tests
[TestClass] public class OrderedDictionaryTests { // ... }
These tests demonstrate the various capabilities of the implemented OrderedDictionary.
Conclusion
While .NET may not provide a generic OrderedDictionary implementation, creating your own with these resources is a viable solution for maintaining both key-based lookup speed and insertion order.
The above is the detailed content of How to Implement a Generic OrderedDictionary in .NET 3.5?. For more information, please follow other related articles on the PHP Chinese website!