Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to Dictionary for doing fast key lookups?

I run into situations where I need to keep track if I've processed a particular value. In these cases, I use Dictionary(Of TKey, TValue) to keep track of the values that I've processed. Basically, as each value is processed, I insert the processed value into as key into the dictionary. When I want to see if I've processed that value, I use the ContainsKey method to see if the value exists in the collection.

This works well, but I do have to insert something in the value side of the key-value pair. I would just use a List(Of T) but I want the performance of the hash table lookup that Dictionary provides. Is there a data collection in .Net that is more suitable for this purpose?

like image 572
poke Avatar asked Dec 30 '12 02:12

poke


2 Answers

I would suggest a HashSet<T>. You could just enter the key, if all you need to know is that the key has already been used.

It's really simple, too:

if (myHashSet.Add(key))
{
    // item wasn't in the hash set, so process it.
}

Add is like "add if not there." It returns true if the item was added. It returns false if the item was already in the collection.

Or, you can use Contains to test, and then Add to add.

like image 159
Jim Mischel Avatar answered Oct 06 '22 01:10

Jim Mischel


On .NET 3.5 or later, you can use a HashSet for that purpose. The methods you need are called Add and Contains. Both operations have time complexity O(log n), as opposed to O(n) for a List.

like image 42
GOTO 0 Avatar answered Oct 06 '22 00:10

GOTO 0