best way to represent this lookup table in c#

10,201

Solution 1

What you actually have is two lookup tables: one by Name and one by Range. There are several ways you can represent these in memory depending on how big the table will get.

The mostly-likely fit for the "by-name" lookup is a dictionary:

var MultiplierByName = new Dictionary<string, double>() { {"Active",.5}, {"Other", 1.0} };

The range is trickier. For that you will probably want to store either just the minimum or the maximum item, depending on how your range works. You may also need to write a function to reduce any given integer to it's corresponding stored key value (hint: use integer division or the mod operator).

From there you can choose another dictionary (Dictionary<int, double>), or if it works out right you could make your reduce function return a sequential int and use a List<double> so that your 'key' just becomes an index.

But like I said: to know for sure what's best we really need to know the scope and nature of the data in the lookup, and the scenario you'll use to access it.

Solution 2

Create a class to represent each row. It would have Name, RangeLow, RangeHigh and Multiplier properties. Create a list of such rows (read from a file or entered in the code), and then use LINQ to query it:

from r in LookupTable
where r.RangeLow <= x && r.RangeHigh >= x
select r.Multiplier;

Solution 3

Sometimes simplicity is best. How many entries are we looking at, and are the ranges integer ranges as you seem to imply in your example? While there are several approaches I can think of, the first one that comes to mind is to maintain two different lookup dictionaries, one for the name and one for the value (range) and then just store redundant info in the range dictionary. Of course, if your range is keyed by doubles, or your range goes into the tens of thousands I'd look for something different, but simplicity rules in my book.

Solution 4

I would implement this using a DataTable, assuming there was no pressing reason to use another datatype. DataTable.Select would work fine for running a lookup on Name or Range. You do lose some performance using a DataTable for this but with 10-15 records would it matter that much.

Share:
10,201
Admin
Author by

Admin

Updated on July 24, 2022

Comments

  • Admin
    Admin almost 2 years

    I need to represent a lookup table in C#, here is the basic structure:

    Name    Range   Multiplier
    
    Active  10-20   0.5
    

    What do you guys suggest?

    I will need to lookup on range and retrieve the multiplier. I will also need to lookup using the name.

    UPdate It will have maybe 10-15 rows in total. Range is integer date type.