在这种情况下我应该使用什么集合?
我正在编写一个类来存储某种表结构。
现在这个表结构中的每一列都有一个名称和一个索引。
现在,该列中的每一行都将被循环遍历,并且 90% 的情况将使用列名称而不是列索引来请求数据。
那么有什么好的数据结构来存储列,以便它可以根据名称非常快速地检索索引。现在我使用一个简单的 string[],但我想知道是否有更快的方法来做到这一点。
部分代码:
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;
}
列的名称在设置后将保持不变,并且它们的长度大多约为 10-16 个字符。
提前致谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于您通常要按名称访问列,因此这听起来是使用将字符串映射到列(字符串数组)的 Map(C# 中的字典类)的好地方。这将允许 O(1) 访问该名称,而不是上面代码中当前的 O(n)。
缺点是您将无法再通过列索引直接访问。然而,这很容易解决——只需保留列名列表并使用它们来建立索引即可! 你可以调用,它仍然是 O(1) 时间。
如果你需要按数字索引,
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
if you ever need to index by number, and it is still O(1) time.
使用
Dictionary
根据列的 ID 存储列的名称。使用您的示例(缺少
_columns
的填充方式):Use a
Dictionary<string,int>
to store the names of the columns against their ID.Using your example (which misses how
_columns
is populated):