Alex Rivera | Logout

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

Asked 2009-12-06T16:43:03.620
9

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?
Edit
Report

1 Answer

0

Load all your values into

var dic = new Dictionary<int, string>();

And use this for retrieval:

string GetDescription(int val)
{
     if(0 <= val && val < 256)
        if(!dic.Contains(val))
           return "Reserved";
        return dic[val];
    throw new ApplicationException("Value must be between 0 and 255");
}
answered 2009-12-06T16:50:56.657

Your Answer