SortedList<Key,Value>
is a slow data structure that you probably shouldn't use at all. You may have already considered using SortedDictionary<Key,Value>
but found it inconvenient because the items don't have indexes (you can't write sortedDictionary[0]
) and because you can write a find nearest key operation for SortedList
but not SortedDictionary
.
But if you're willing to switch to a third-party library, you can get better performance by changing to a different data structure.
The Loyc Core libraries include a data type that works the same way as SortedList<Key,Value>
but is dramatically faster when the list is large. It's called BDictionary<Key,Value>
.
Now, answering your original question: yes, the way you wrote the code, it performs two searches and one insert (the insert is the slowest part). If you switch to BDictionary
, there is a method bdictionary.AddIfNotPresent(key, value)
which combines those two operations into a single operation. It returns true if the specified item was added, or false if it was already present.