Open micampbell opened 11 months ago
Tagging subscribers to this area: @dotnet/area-system-collections See info in area-owners.md if you want to be subscribed.
Wouldn't an IEnumerable parameter suffice in this case? We can always use runtime checks to infer the input size if available.
I thought of that as well, but was trying to minimize change to constructor body. It's definitely something that could be added. But mainly, I'm pleased to hear of your quick reply and (potential) confirmation that this is a valid request.
Background and motivation
SortedList still has value in many scenarios (despite overlap with PriorityQueue and Linq sorting methods). SortedList is preferred over other collections: when most of the data is provided upfront (at the constructor), when performing common list indexing and when duplicate keys are unavoidable. However, no constructor allows for receiving keys and values outside of the one receiving a dictionary (which does not allow for duplicate keys). The current solution is to add the key and value through the Add method, which is slower than the single Array.Sort performed in the constructor. Therefore, one or two new constructors are recommended for SortedList that can receive the keys and values without the need for a dictionary as input.
API Proposal
This is an easy modification since the existing constructor (https://github.com/dotnet/runtime/blob/bed122bb15c5136d4f1aa2e8e9c44608dbbebc8f/src/libraries/System.Collections/src/System/Collections/Generic/SortedList.cs#L149) only references the dictionary to get the count and to copy the keys and values arrays. This could call another constructor which either 1) receives the keys and values as separate arguments, 2) receives them as ICollection.
So, it is proposed to replace the above-referenced constructor with the following:
API Usage
As an example, I may have a list of items that I will evaluate to a metric upon which I would like to sort.
Alternative Designs
n/a
Risks
The risk is that the collection of keys and values may not line up directly. The alternative is to allow the existing constructor to receive ICollection as opposed to IDictionary. This is implemented in the new code above but requires that some changes be made to the constructor body to separate the KeyValuePair. This is done by using Linq's Select() and ToArray() methods.