0

There a dictionary object that gets loaded with the following key values: 119 189a 189b 189c 197 201a 201b

In most situations, life is good and all the individual key values are needed/unique. But in certain situations, the keys with letters behind them (ie...189a, 189b, 189c) all mean the same thing (ie...189). So I need a way to see if a key value exists (like the containskey method) for only the first part of the key and then return true.
Any ideas on how to accomplish this?

user1070202
  • 157
  • 1
  • 4
  • The lookup would be `O(n)` which would probably defeat the whole purpose of a hash table in the first place. – Mike Christensen Apr 05 '12 at 15:44
  • Alternatively if vb.net is relatively object-oriented, then you could create your own class you use for the key and define its hash and equals methods appropriately so that 189a, 189b and 189c are all "equal". – Jesus is Lord Apr 05 '12 at 15:47
  • @MikeChristensen Depending on the frequency and nature of the lookup, it may not be a big deal. It isn't clear from the question that the existence check for a key with a specified format is a regular use of the collection. If it isn't, than using a non-hashed set can be perfectly legitimate. – PinnyM Apr 05 '12 at 16:41

2 Answers2

1

Something like this?

dictionary.Keys.Any(Function(key) key.StartsWith("189"))

or you can use a Regex for more find-grained control:

dictionary.Keys.Any(Function(key) Regex.IsMatch(key, "^189[^\d]?")
PinnyM
  • 35,165
  • 3
  • 73
  • 81
  • Note this question was tagged with `VB.Net` – Mike Christensen Apr 05 '12 at 15:46
  • That actually works very well. The only problem I could foresee is if the dictionary also contained a value of "1891" and then it would trigger a false positive. Would it be better to try to filter out the letter at the end; since it will only have a possiblity of a single letter at the end of the number (or no letter at all)? – user1070202 Apr 05 '12 at 16:17
  • @user1070202: I would recommend simply not storing the letter in the key. You will only have to check the last character in the key to remove it if it is an alphabet. And then your standard Dictionary.Contains should work. – Shrieks Apr 05 '12 at 19:23
1

Since you only sometimes need ignore the suffixed letter, for the greatest efficiency, I would recommend using an additional HashSet(T) to store the numeric portion. When you add/remove elements from your dictionary, also add/remove the numeric from the HashSet(T). HashSet(T).Contains method is O(1), so checking to see if an element exists will be quick.

Timiz0r
  • 1,304
  • 7
  • 7