0

My situation is that I'm making a messaging system for a component based system where messages can be looked up/sent by either an integer or string value. I'd like to use the string values for local code because it's easier to handle, and I'd like integer values to be used so I can send messages over a network instead of a string value.

Normally I'd use an enum for easy reference and keep everything integer-based, but I want this to be dynamic so that I can add or remove message types and values.

I figure I need to use a dictionary with an integer key and string value, but i'm trying to figure out if I will run into performance issues searching by value instead of searching by key. I shouldn't need to worry about unique values (i'll use a hashset to make sure they are all unique).

BLUF: do I need to worry about performance issues when getting an item by value instead of by key?

David Torrey
  • 1,335
  • 3
  • 20
  • 43

3 Answers3

4

You could just as easily have two Dictionaries, one from int -> string and one from string -> int.

DavidN
  • 5,117
  • 2
  • 20
  • 15
  • And encapsulate it in a class so you don't forget to keep the two collections in sync – lc. Aug 07 '13 at 14:47
  • thanks, your explanation and the one Namfuak linked to are essentially the same; I gave you a +1 and him the nod since he also mentioned performance – David Torrey Aug 07 '13 at 15:01
3

You lose out on the advantage of a dictionary (O(1) time lookups), since the values are not hashed. So, you'll get the lookup time of a normal list (O(log n) with a Binary Search).

Jon Skeet posted a code solution for a bi-directional dictionary in this link, if you are interested:

Getting key of value of a generic Dictionary?

Community
  • 1
  • 1
IllusiveBrian
  • 3,105
  • 2
  • 14
  • 17
0

If there is not too much data then it's fine to scan values.

If there is a lot of data and a lot of operations then either use DavidN's suggestion or copy the code from this one for multi-key dictionary:

Multi-key dictionary in c#?

There is a lot of suggestions there - I suggest scrolling down

Community
  • 1
  • 1
Wojtek Turowicz
  • 4,086
  • 3
  • 27
  • 38