Reputation: 235
In my application, I have a SortedDictionary
. Most of the time, Im inserting single values in it - in such cases, I understand, that it needs to use Compare method to determine, where should the new value be added.
I was just wondering, whether there is some way I can initialize this SortedDictionary from lets say a KeyValuePair<>[]
array, without causing Compare method to run.
The thing is, that sometimes I do have a KeyValuePair<>[]
array, that contains already sorted Keys and so it could be transformed in SortedDictionary
without any additional sorting. I understand that compiler doesnt know that my collection is sorted, but since Im sure of it, is there some way to intentionaly evade the comparison? If this request is total nonsense, could you please explain why?
The only reason I want to this is because of performance - when working with big collections, the Compare method takes some time to finish.
Upvotes: 0
Views: 540
Reputation: 64923
[...] I understand that compiler doesnt know that my collection is sorted, [...]
Sorting isn't a compile-time but run-time detail.
I don't think this would be a good idea. Here's a good summary of reasons to don't do it:
At the end of the day, when you need a collection where its order is the insertion order, you should use a List<T>
, and in your case, you should consider a List<KeyValuePair<TKey, TValue>>
. Anyway, this won't work in your case. You want to provide an already sorted sequence as source of a sorted dictionary, and let the comparer work once the dictionary is filled when adding new pairs after construction-time.
I would say that if you need a sorted dictionary which relies on a sequence of pairs given during construction-time and that mustn't be re-sorted (since they're already sorted), then you'll need to think about rolling your own IDictionary<TKey, TValue>
implementation to provide such feature...
Upvotes: 1