Skip to content

[API Proposal]: Add a generic OrderedDictionary class #24826

Closed

Description

@TylerBrinkley

EDITED on 4/10/2024 by @stephentoub to update proposal

Often times I've come across places when needing a Dictionary where the insertion order of the elements is important to me. Unfortunately, .NET does not currently have a generic OrderedDictionary class. We've had a non-generic OrderedDictionary class since .NET Framework 2.0 which oddly enough was when generics were added but no generic equivalent. This has forced many to roll their own solution, typically by using a combination of a List and Dictionary field resulting in the worst of both worlds in terms of performance and resulting in larger memory usage, and even worse sometimes users instead rely on implementation details of Dictionary for ordering which is quite dangerous.

Proposed API

namespace System.Collections.Generic;

public class OrderedDictionary<TKey, TValue> :
    IDictionary<TKey, TValue>, IReadOnlyDictionary<TKey, TValue>, IDictionary,
    IList<KeyValuePair<TKey, TValue>>, IReadOnlyList<KeyValuePair<TKey, TValue>>, IList
    where TKey : not null
{
    public OrderedDictionary();
    public OrderedDictionary(int capacity);
    public OrderedDictionary(IEqualityComparer<TKey>? comparer);
    public OrderedDictionary(int capacity, IEqualityComparer<TKey>? comparer);
    public OrderedDictionary(IDictionary<TKey, TValue> dictionary);
    public OrderedDictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey>? comparer);
    public OrderedDictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection);
    public OrderedDictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection, IEqualityComparer<TKey>? comparer);

    public IEqualityComparer<TKey> Comparer { get; }
    public OrderedDictionary<TKey, TValue>.KeyCollection Keys { get; }
    public OrderedDictionary<TKey, TValue>.ValueCollection Values { get; }
    public int Count { get; }
    public TValue this[TKey key] { get; set; }

    public void Add(TKey key, TValue value);
    public void Clear();
    public bool ContainsKey(TKey key);
    public bool ContainsValue(TValue value);
    public KeyValuePair<TKey, TValue> GetAt(int index);
    public OrderedDictionary<TKey, TValue>.Enumerator GetEnumerator();
    public int IndexOf(TKey key);
    public void Insert(int index, TKey key, TValue value);
    public bool Remove(TKey key);
    public bool Remove(TKey key, [MaybeNullWhen(false)] out TValue value);
    public void RemoveAt(int index);
    public void SetAt(int index, TValue value);
    public void SetAt(int index, TKey key, TValue value);
    public void TrimExcess();
    public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value);

    public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>
    {
        public KeyValuePair<TKey, TValue> Current { get; }
        public void Dispose();
        public bool MoveNext();
    }

    public sealed class KeyCollection : IList<TKey>, IReadOnlyList<TKey>, IList
    {
        public int Count { get; }
        public bool Contains(TKey key);
        public void CopyTo(TKey[] array, int arrayIndex);
        public OrderedDictionary<TKey, TValue>.KeyCollection.Enumerator GetEnumerator();

        public struct Enumerator : IEnumerator<TKey>
        {
            public TKey Current { get; }
            public bool MoveNext();
            public void Dispose();
        }
    }

    public sealed class ValueCollection : IList<TValue>, IReadOnlyList<TValue>, IList
    {
        public int Count { get; }
        public void CopyTo(TValue[] array, int arrayIndex);
        public OrderedDictionary<TKey, TValue>.ValueCollection.Enumerator GetEnumerator();

        public struct Enumerator : IEnumerator<TValue>
        {
            public TValue Current { get; }
            public bool MoveNext();
            public void Dispose();
        }
    }
}

Perhaps one of the reasons there was no generic OrderedDictionary added initially was due to issues with having both a key and index indexer when the key is an int. A call to the indexer would be ambiguous. Roslyn prefers the non-generic parameter so in this case the index indexer will be called.

API Details

  • Insert allows index to be equal to Count to insert the element at the end.
  • SetAt(int index, TValue value) requires index to be less than Count but SetAt(int index, TKey key, TValue value) allows index to be equal to Count similar to Insert.
  • Performance will be the same as Dictionary for all operations except Remove which will necessarily be O(n). Insert and RemoveAt which aren't members of Dictionary will also be O(n).

Open Questions

  • Should the namespace be System.Collections.Generic when it could easily be System.Collections.Specialized where the non-generic version is located? I just felt this collection is far more useful to be relegated to that namespace.
  • Should the non-generic interfaces ICollection, IList, and IOrderedDictionary be implemented?

Updates

  • Added constructor overloads for IEnumerable<KeyValuePair<TKey, TValue>>.
  • Added ContainsValue method due to being needed for the ValueCollection.Contains method.
  • Proposal no longer advocates for throwing an exception when using an indexer while the key is an int.

Activity

  1. sharwell commented on Jan 29, 2018

    @sharwell
    Contributor

    📝 Technically SortedList<TKey, TValue> is an ordered dictionary. My implementation of SortedTreeDictionary<TKey, TValue> is based on the API from this type.

    Edit: (And removing my related comments that followed) I was not aware of the semantics of the non-generic OrderedDictionary when I posted this. I was instead thinking this request was either for SortedList<TKey, TValue> or for something like LinkedHashMap<K, V>. The OrderedDictionary.Insert method semantics cleared things up for me.

  2. TylerBrinkley commented on Jan 29, 2018

    @TylerBrinkley
    ContributorAuthor

    @sharwell SortedList and SortedDictionary are not hash tables but trees resulting in O(log(n)) lookups instead of O(1) for Dictionary.

  3. TylerBrinkley commented on Jan 29, 2018

    @TylerBrinkley
    ContributorAuthor

    Related to dotnet/corefx#26638

  4. danmoseley commented on Jan 31, 2018

    @danmoseley
    Contributor

    Would the implementation optimize for retrieval (presumably array + hashtable) or for space (presumably a tree/heap) ? Are there scenarios for both? What complexity do you hope for for lookup, Add, Remove, and ContainsKey (and ContainsValue if we have that)

    [snipped example table in favor of @TylerBrinkley 's below]

  5. TylerBrinkley commented on Jan 31, 2018

    @TylerBrinkley
    ContributorAuthor

    Thanks for putting that chart together. The implementation will be nearly identical to Dictionary<K,V> with a bucket and entries array except the entries in the entries array will be contiguous and ordered.

    Below is the chart filled out

    Operation Dictionary<K,V> SortedDictionary<K,V> SortedList<K,V> OrderedDictionary<K,V>
    this[key] O(1) O(log n) O(log n) or O(n) O(1)
    this[index] n/a n/a n/a O(1)
    Add(key,value) O(1) O(log n) O(n) O(1)
    Remove(key) O(1) O(log n) O(n) O(n)
    RemoveAt(index) n/a n/a n/a O(n)
    ContainsKey(key) O(1) O(log n) O(log n) O(1)
    ContainsValue(value) O(n) O(n) O(n) O(n)
    IndexOf(key) n/a n/a n/a O(1)
    Insert(index,key,value) n/a n/a n/a O(n)
    Space efficiency good worst medium good
    Insert/Remove sorted data n/a O(log n) O(n) n/a
    From sorted data n/a ? better? n/a
  6. sharwell commented on Jan 31, 2018

    @sharwell
    Contributor

    💭 I almost prefer the indexer for this type be based on the "bias" implied by the type name. To me, OrderedDictionary<TKey, TValue> would bias towards dictionary, which means this[key] would be the only indexer. Indexed access could be achieved by calling GetAt(index) or by casting to IList<TValue> (or IList<KeyValuePair<TKey, TValue>>?) and using the indexer there.

  7. TylerBrinkley commented on Jan 31, 2018

    @TylerBrinkley
    ContributorAuthor

    If we only have one I'd agree that the this[key] indexer would be the one to stay. Like you said, indexed access could still be achieved with the GetAt and SetAt methods and then the GetValue and SetValue methods could be removed. I'm torn on this because a this[index] indexer would be very intuitive to users and a vast majority of time would not be an issue.

  8. TylerBrinkley commented on Feb 6, 2018

    @TylerBrinkley
    ContributorAuthor

    FYI, if this gets approved I'd happily implement it.

  9. JustArchi commented on May 15, 2018

    @JustArchi
    Contributor

    I'd also be interested in seeing generic variant of OrderedDictionary, I was seriously confused when I found out that there is no such thing as of now, while non-generic version already exists.

    Thank you in advance for considering this.

  10. prajaybasu commented on Jul 3, 2018

    @prajaybasu

    Hello, I too would like to see a generic version of this, and have it moved to the System.Collections.Generic namespace.
    A quick Google Search shows that the generic version is implemented by a lot of library authors themselves:

    and so on..

    So it would be nice to have this type implemented in the framework.

  11. shaggygi commented on Jul 22, 2018

    @shaggygi
    Contributor

    I still think it would be beneficial to have Immutable Parent/Child Collection, but understand it is not specifically related to this thread.

  12. wanton7 commented on Aug 23, 2018

    @wanton7

    Just had need for this today. Any news if/when this will be implemented?

  13. TylerBrinkley commented on Aug 28, 2018

    @TylerBrinkley
    ContributorAuthor

    Moved to corefxlab#2456 as part of the specialized collections initiative.

  14. transferred this issue fromdotnet/corefxon Jan 31, 2020
  15. 37 remaining items

  16. TylerBrinkley commented on Apr 10, 2024

    @TylerBrinkley
    ContributorAuthor

    Thanks, yeah I agree it would likely cause issues for some users and using the GetAt and SetAt methods instead is not too burdensome even if it wouldn't be necessary for most collections when TKey is not an int.

  17. modified the milestones: Future, 9.0.0 on Apr 21, 2024
  18. self-assigned this
    on Apr 21, 2024
  19. added
    blockingMarks issues that we want to fast track in order to unblock other important work
    and removed
    blockingMarks issues that we want to fast track in order to unblock other important work
    on May 12, 2024
  20. changed the title [-]Add a generic OrderedDictionary class[/-] [+][API Proposal]: Add a generic OrderedDictionary class[/+] on May 20, 2024
  21. terrajobst commented on Jun 11, 2024

    @terrajobst
    Contributor

    Video

    • Looks good as proposed
    • We might want to add an overload of GetAt()/SetAt that takes Index
    • Should probably go into System.Collections.dll
    namespace System.Collections.Generic;
    
    public class OrderedDictionary<TKey, TValue> :
        IDictionary<TKey, TValue>, IReadOnlyDictionary<TKey, TValue>, IDictionary,
        IList<KeyValuePair<TKey, TValue>>, IReadOnlyList<KeyValuePair<TKey, TValue>>, IList
        where TKey : not null
    {
        public OrderedDictionary();
        public OrderedDictionary(int capacity);
        public OrderedDictionary(IEqualityComparer<TKey>? comparer);
        public OrderedDictionary(int capacity, IEqualityComparer<TKey>? comparer);
        public OrderedDictionary(IDictionary<TKey, TValue> dictionary);
        public OrderedDictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey>? comparer);
        public OrderedDictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection);
        public OrderedDictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection, IEqualityComparer<TKey>? comparer);
    
        public IEqualityComparer<TKey> Comparer { get; }
        public OrderedDictionary<TKey, TValue>.KeyCollection Keys { get; }
        public OrderedDictionary<TKey, TValue>.ValueCollection Values { get; }
        public int Count { get; }
        public TValue this[TKey key] { get; set; }
    
        public void Add(TKey key, TValue value);
        public void Clear();
        public bool ContainsKey(TKey key);
        public bool ContainsValue(TValue value);
        public KeyValuePair<TKey, TValue> GetAt(int index);
        public OrderedDictionary<TKey, TValue>.Enumerator GetEnumerator();
        public int IndexOf(TKey key);
        public void Insert(int index, TKey key, TValue value);
        public bool Remove(TKey key);
        public bool Remove(TKey key, [MaybeNullWhen(false)] out TValue value);
        public void RemoveAt(int index);
        public void SetAt(int index, TValue value);
        public void SetAt(int index, TKey key, TValue value);
        public void TrimExcess();
        public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value);
    
        public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>
        {
            public KeyValuePair<TKey, TValue> Current { get; }
            public void Dispose();
            public bool MoveNext();
        }
    
        public sealed class KeyCollection : IList<TKey>, IReadOnlyList<TKey>, IList
        {
            public int Count { get; }
            public bool Contains(TKey key);
            public void CopyTo(TKey[] array, int arrayIndex);
            public OrderedDictionary<TKey, TValue>.KeyCollection.Enumerator GetEnumerator();
    
            public struct Enumerator : IEnumerator<TKey>
            {
                public TKey Current { get; }
                public bool MoveNext();
                public void Dispose();
            }
        }
    
        public sealed class ValueCollection : IList<TValue>, IReadOnlyList<TValue>, IList
        {
            public int Count { get; }
            public void CopyTo(TValue[] array, int arrayIndex);
            public OrderedDictionary<TKey, TValue>.ValueCollection.Enumerator GetEnumerator();
    
            public struct Enumerator : IEnumerator<TValue>
            {
                public TValue Current { get; }
                public bool MoveNext();
                public void Dispose();
            }
        }
    }
  22. added
    api-approvedAPI was approved in API review, it can be implemented
    and removed
    api-ready-for-reviewAPI is ready for review, it is NOT ready for implementation
    on Jun 11, 2024
  23. added
    in-prThere is an active PR which will close this issue when it is merged
    on Jun 11, 2024
  24. kronic commented on Jun 12, 2024

    @kronic
    Contributor

    @stephentoub @terrajobst
    Maybe it's worth adding more methods

    public void Move(int oldIndex, int newIndex);
    public void MoveRange(int fromIndex, int toIndex, int count);
    public void Stort(IComparer<TValue> comparer);
  25. AndriySvyryd commented on Jun 12, 2024

    @AndriySvyryd
    Member

    Also consider these methods, that can be more efficient if implemented in the type itself.

    int EnsureCapacity(int capacity)
    void TrimExcess(int capacity)
    TValue GetOrAdd(TKey key, TValue value)
    TValue GetOrAdd(TKey key, Func<TValue> valueFactory)
    bool TryAdd(TKey key, TValue value)
  26. locked and limited conversation to collaborators on Jul 14, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

api-approvedAPI was approved in API review, it can be implementedarea-System.Collectionsin-prThere is an active PR which will close this issue when it is merged

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions