Stephen Holt
Stephen Holt

Reputation: 2368

Is Dictionary the best way to record presence or absence of a key

Apologies if this has already been asked elsewhere, but I couldn't find it.

I want to store a set of strings in .NET, in such as way that they can be easily and quickly looked up to find if the key is stored or not.

I could just use a List<string> and enumerate the list every time I need to search, but obviously that linear search is quite inefficient.

So my next thought is to use a Dictionary<string, object> and query that each time, which should hopefully result in some cool string hashing and faster search times. However, I'm not actually storing anything in the "object" part of the dictionary so it seems like there might be an inefficiency there.

Is there any better way to do this?

Upvotes: 3

Views: 182

Answers (3)

cgon
cgon

Reputation: 1981

If your dictionary object is being used by multiple threads, ConcurrentDictionary(Of TKey, TValue) is be a better choice.

Upvotes: 0

brgerner
brgerner

Reputation: 4371

HashSet<string> for unordered sets or
SortedSet<string> if order is importent.

Upvotes: 2

SLaks
SLaks

Reputation: 887957

You're looking for a HashSet<string>, which provides the same O(1) performance of a dictionary, but without those pesky values.

Upvotes: 10

Related Questions