Home > Backend Development > C++ > How to Implement a Generic OrderedDictionary in .NET 3.5?

How to Implement a Generic OrderedDictionary in .NET 3.5?

Mary-Kate Olsen
Release: 2024-12-31 11:17:10
Original
230 people have browsed it

How to Implement a Generic OrderedDictionary in .NET 3.5?

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 does, effectively creating a hybrid of IList and IDictionary.

Interface

public interface IOrderedDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IOrderedDictionary
{
    // ...
}
Copy after login

Implementation

public class OrderedDictionary<TKey, TValue> : IOrderedDictionary<TKey, TValue>
{
    private KeyedCollection2<TKey, KeyValuePair<TKey, TValue>> _keyedCollection;
    
    // ...
}
Copy after login

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
{
    // ...
}
Copy after login

Tests

[TestClass]
public class OrderedDictionaryTests
{
    // ...
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template