What is the most efficient way to do look-up table in C#

Maestro1024 picture Maestro1024 · Dec 6, 2009 · Viewed 30.4k times · Source

What is the most efficient way to do look-up table in C#

I have a look-up table. Sort of like

0 "Thing 1"
1 "Thing 2"
2 "Reserved"
3 "Reserved"
4 "Reserved"
5 "Not a Thing"

So if someone wants "Thing 1" or "Thing 2" they pass in 0 or 1. But they may pass in something else also. I have 256 of these type of things and maybe 200 of them are reserved.

So what is the most efficient want to set this up?

  • A string Array or dictionary variable that gets all of the values. And then take the integer and return the value at that place.

One problem I have with this solution is all of the "Reserved" values. I don't want to create those redundant "reserved" values. Or else I can have an if statement against all of the various places that are "reserved" but they might now be just 2-3, might be 2-3, 40-55 and all different places in the byte. This if statement would get unruly quick

  • My other option that I was thinking was a switch statement. And I would have all of the 50ish known values and would fall through through and default for the reserved values.

I am wondering if this is a lot more processing than creating a string array or dictionary and just returning the appropriate value.

  • Something else? Is there another way to consider?

Answer

Jonas Elfström picture Jonas Elfström · Dec 6, 2009

"Retrieving a value by using its key is very fast, close to O(1), because the Dictionary(TKey, TValue) class is implemented as a hash table."

var things = new Dictionary<int, string>();
things[0]="Thing 1";
things[1]="Thing 2";
things[4711]="Carmen Sandiego";