Search code examples
c#.netsearchkeysortedlist

Which is the best way to find if a key exists in C# SortedList?


Which is the best way to find if a key exists in C# SortedList?

The question is quite clear, I have a SortedList represents an associated array. Both key and values are string. I'm thinking of scanning linear but binary search is faster coz it's 'Sorted'.

I wonder if there's a standard way to find the pair by key, like noted in MSDN or some where popular?


Solution

  • ContainsKey is the best way to find out if a key exists. It is already optimized, there is no need for you to make a custom search algorithm:

    "This method uses a binary search algorithm; therefore, this method is an O(log n) operation, where n is Count."