Setting the i-th SortedDictionary value

I need to set the value of an element in my sortedDictionary that the index is referring to.

those.

sortedDictionary.Values[index] = value; // compile error

      

Note that the following is not correct as it is requested by key, not index.

sortedDictionary[index] = value; // incorrect

      

I came up with the following solution, but my intuition tells me that it is slow. I am assuming key access is O (log N) and index access is O (1), but I'm not sure.

sortedDictionary[sortedDictionary.ElementAt(index).Key] = value;

      

Some background:

I use SortedDictionary because I need fast inserts, deletes, searches and the ability to access neighboring elements. (i.e. next high or next low). Efficiency is important.

+2


source to share


1 answer


This is a bit of a compromise.

You can use SortedList and get a fast index search, but you will sacrifice insert speed.

To quote MSDN :



... Another difference between SortedDictionary<(Of <(TKey, TValue>)>)

and SortedList<(Of <(TKey, TValue>)>)

is that   SortedList<(Of <(TKey, TValue>)>

) supports efficient indexed lookups for keys and values ​​across the collections returned by keys and Value properties. This is not necessary to restore lists when accessing properties, since lists are just wrappers for internal arrays of keys and values.

Both SortedDictionary

and SortedList

implemented IDictionary

, so I would get some test data and code profiler together and try both.

If not fast enough, you may need to start using Dictionary

(fast inserts, updates and key lookups) and manually maintain the index on the second data structure.

+2


source







All Articles