带索引的字典 [英] Dictionary with index
问题描述
大家好,
我需要一个具有索引的字典类型.
这意味着除了单词及其含义之外,每个条目还必须具有一个索引,通过它我也可以访问该定义.
这是解决方案:
class IndexedDictionary< KEY,VALUE> :System.Collections.Generic.Dictionary< KEY,VALUE> { 公共 VALUE 此 [ int 索引] { 获取 {返回索引[index]; }} 新 公共 void 添加(KEY键, VALUE 值){ 基本.添加(键,值); RebuildIndex(); } // 添加 新 公共 无效 Remove(关键) { 基本.删除(关键字); RebuildIndex(); } // AddRange 新 公共 void Clear(){ 基本 .Clear(); RebuildIndex(); } // 清除 无效 RebuildIndex(){ 索引= 新 VALUE [此 .Keys.Count]; 如果(此 .Values.Count > 0 ) this .Values.CopyTo(Index, 0 ); } // RebuildIndex KEY [] Index = 新 KEY [ 0 ]; } // IndexedDictionary
当您读取日志但更新较少时,此解决方案有效,因为Add/Remove/Clear
有点昂贵.注意new
说明符的重要性;它有助于消除警告.如果需要,可以修改此代码以返回KeyValuePair
或KEY
.
—SA
这是替代解决方案:
class IndexedDictionary< KEY,VALUE> :System.Collections.Generic.Dictionary< KEY,VALUE> { 公共 VALUE 此 [ int 索引] { 获取 {返回 GetValueByIndex(index); }} VALUE GetValueByIndex( int 索引){ int current = 0 ; foreach (VALUEs 值 值中){ 如果(当前==索引) 返回 值; ++索引; } 抛出 新 System.IndexOutOfRangeException(); } // GetByIndex */ } // IndexedDictionary
此解决方案较为简单,它不使用任何冗余且不会降低Add/Remove/Clear
的速度,但在this
索引器上的速度却很慢-速度与O(N)一样慢(请参阅 ^ ]).
—SA
如果您插入的次数相对较少,键支持排序,并且O(log N)可以正常访问,则可以尝试排序列表 [ 解决方案
Here is the solution:
class IndexedDictionary<KEY, VALUE> : System.Collections.Generic.Dictionary<KEY, VALUE> { public VALUE this[int index] { get { return Index[index]; } } new public void Add(KEY key, VALUE value) { base.Add(key, value); RebuildIndex(); } //Add new public void Remove(KEY key) { base.Remove(key); RebuildIndex(); } //AddRange new public void Clear() { base.Clear(); RebuildIndex(); } //Clear void RebuildIndex() { Index = new VALUE[this.Keys.Count]; if (this.Values.Count > 0) this.Values.CopyTo(Index, 0); } //RebuildIndex KEY[] Index = new KEY[0]; } //IndexedDictionary
This solution is effective when you read it a log but update less, asAdd/Remove/Clear
is a bit costly. Pay attention for the importance ofnew
specifier; it helps to remove the warning. If you want you can modify this code to returnKeyValuePair
orKEY
.
—SA
This is alternative solution:
class IndexedDictionary<KEY, VALUE> : System.Collections.Generic.Dictionary<KEY, VALUE> { public VALUE this[int index] { get { return GetValueByIndex(index); } } VALUE GetValueByIndex(int index) { int current = 0; foreach (VALUE value in Values) { if (current == index) return value; ++index; } throw new System.IndexOutOfRangeException(); } //GetByIndex */ } //IndexedDictionary
This solution is simpler, it does not use any redundancy and does not slow downAdd/Remove/Clear
but is slow onthis
indexer — as slow as O(N) (see http://en.wikipedia.org/wiki/Big_O_notation[^]).
—SA
If you insert relatively infrequently, your keys support ordering, and O(log N) access is OK for your purposes, you can try SortedList[^]: it supports both indexed retrieval (mySortedList.Values[myIndex]) and retrieval by key (mySortedList[myKey]).
这篇关于带索引的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!