Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better data structure than dictionary for key existence

Tags:

c#

I often want to optimize the performance of a .Contains on a collection.

I have always done this by creating a Dictionary<TKey,bool> and then using .ContainsKey on the dictionary to give O(1) .Contains performance.

However it always irks me that I actually don't care at all about the value in the dictionary.

Is there a better data structure than dictionary to support this case where I don't care about the actual value, only the existence of the key?

like image 529
Not loved Avatar asked Mar 18 '14 00:03

Not loved


1 Answers

HashSet has a method Contains which is an O(1) search of the values. This should suffice (assuming your TKey implements GetHashCode correctly) :)

like image 129
Xenolightning Avatar answered Sep 19 '22 04:09

Xenolightning