views:

1940

answers:

4

Hi,

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.

+2  A: 

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.

WaldenL
+3  A: 

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;
John Saunders
Correct me if I'm wrong, but isn't this a fancy linear search?
Juliet
For O(10) items, linear search will probably be faster than anything fancier.
MarkusQ
The poster said "lookup table", which suggests a small number of rows. Obviously, if a large number of rows will be present, then some form of index should be used.
John Saunders
+4  A: 

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.

Joel Coehoorn
A: 

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.

Jeremy Bade