Reputation: 6249
I'm writing a class to store some kind of a table-structure.
Now each column in this table structure has a name, and an index.
Now each row in this column will be looped through, and the data will 90% of the cases be requested using the name of the column rather then the index of it.
So what's a good data structure to store the columns, so that it can retrieve the index very quickly based upon the name. Right now I'm using a simple string[], but I wonder if there are faster ways to do this.
Parts of the code:
private string[] _columns;
private int _width;
private int getIndex(string columnName)
{
for (int i = 0; i < _width; i++)
{
if (_columns[i] == columnName) return i;
}
return -1;
}
The names of the columns will be constant after they've been set, and they're mostly about 10-16 characters long.
Thanks in advance.
Upvotes: 0
Views: 91
Reputation: 6054
Since you are usually going to access columns by the name, this sounds like a good place to use a Map (Dictionary class in C#) that maps Strings to Columns (String arrays). That would allow O(1) access for the name rather than the current O(n) in the above code.
The disadvantage is that you wouldn't be able to access directly by column index anymore. However, this is simple to solve--just keep your list of column names and use those to index! You can then call
_columnsMap[_columns[index]]
if you ever need to index by number, and it is still O(1) time.
Upvotes: 3
Reputation: 499002
Use a Dictionary<string,int>
to store the names of the columns against their ID.
Using your example (which misses how _columns
is populated):
private IDictionary<string,int> _columns;
private int _width;
private int getIndex(string columnName)
{
return _columns[columnName];
}
Upvotes: 1