Repository navigation
Description
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
Insertallowsindexto be equal toCountto insert the element at the end.SetAt(int index, TValue value)requiresindexto be less thanCountbutSetAt(int index, TKey key, TValue value)allowsindexto be equal toCountsimilar toInsert.- Performance will be the same as
Dictionaryfor all operations exceptRemovewhich will necessarily beO(n).InsertandRemoveAtwhich aren't members ofDictionarywill also beO(n).
Open Questions
- Should the namespace be
System.Collections.Genericwhen it could easily beSystem.Collections.Specializedwhere 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, andIOrderedDictionarybe implemented?
Updates
- Added constructor overloads for
IEnumerable<KeyValuePair<TKey, TValue>>. - Added
ContainsValuemethod due to being needed for theValueCollection.Containsmethod. - Proposal no longer advocates for throwing an exception when using an indexer while the key is an int.
Activity
sharwell commentedon Jan 29, 2018
📝
TechnicallySortedList<TKey, TValue>is an ordered dictionary. My implementation ofSortedTreeDictionary<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
OrderedDictionarywhen I posted this. I was instead thinking this request was either forSortedList<TKey, TValue>or for something likeLinkedHashMap<K, V>. TheOrderedDictionary.Insertmethod semantics cleared things up for me.TylerBrinkley commentedon Jan 29, 2018
@sharwell
SortedListandSortedDictionaryare not hash tables but trees resulting inO(log(n))lookups instead ofO(1)forDictionary.TylerBrinkley commentedon Jan 29, 2018
Related to dotnet/corefx#26638
danmoseley commentedon Jan 31, 2018
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]
TylerBrinkley commentedon Jan 31, 2018
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
sharwell commentedon Jan 31, 2018
💭 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 meansthis[key]would be the only indexer. Indexed access could be achieved by callingGetAt(index)or by casting toIList<TValue>(orIList<KeyValuePair<TKey, TValue>>?) and using the indexer there.TylerBrinkley commentedon Jan 31, 2018
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 theGetAtandSetAtmethods and then theGetValueandSetValuemethods could be removed. I'm torn on this because athis[index]indexer would be very intuitive to users and a vast majority of time would not be an issue.TylerBrinkley commentedon Feb 6, 2018
FYI, if this gets approved I'd happily implement it.
JustArchi commentedon May 15, 2018
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.
prajaybasu commentedon Jul 3, 2018
Hello, I too would like to see a generic version of this, and have it moved to the
System.Collections.Genericnamespace.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.
shaggygi commentedon Jul 22, 2018
I still think it would be beneficial to have Immutable Parent/Child Collection, but understand it is not specifically related to this thread.
wanton7 commentedon Aug 23, 2018
Just had need for this today. Any news if/when this will be implemented?
TylerBrinkley commentedon Aug 28, 2018
Moved to corefxlab#2456 as part of the specialized collections initiative.
37 remaining items
TylerBrinkley commentedon Apr 10, 2024
Thanks, yeah I agree it would likely cause issues for some users and using the
GetAtandSetAtmethods instead is not too burdensome even if it wouldn't be necessary for most collections whenTKeyis not anint.[-]Add a generic OrderedDictionary class[/-][+][API Proposal]: Add a generic OrderedDictionary class[/+]terrajobst commentedon Jun 11, 2024
Video
GetAt()/SetAtthat takesIndexSystem.Collections.dllkronic commentedon Jun 12, 2024
@stephentoub @terrajobst
Maybe it's worth adding more methods
AndriySvyryd commentedon Jun 12, 2024
Also consider these methods, that can be more efficient if implemented in the type itself.