【发布时间】:2011-10-08 02:58:17
【问题描述】:
我正在寻找一种与通用字典的 Keys 属性(KeyCollection 类型)一样高效的方法。
使用 Linq select 语句会起作用,但每次请求键时它都会遍历整个集合,而我相信键可能已经在内部存储了。
目前我的 GenericKeyedCollection 类如下所示:
public class GenericKeyedCollection<TKey, TItem> : KeyedCollection<TKey, TItem> {
private Func<TItem, TKey> getKeyFunc;
protected override TKey GetKeyForItem(TItem item) {
return getKeyFunc(item);
}
public GenericKeyedCollection(Func<TItem, TKey> getKeyFunc) {
this.getKeyFunc = getKeyFunc;
}
public List<TKey> Keys {
get {
return this.Select(i => this.GetKeyForItem(i)).ToList();
}
}
}
更新:感谢您的回答,因此我将使用以下属性而不是使用 Linq 进行迭代。
public ICollection<TKey> Keys {
get {
if (this.Dictionary != null) {
return this.Dictionary.Keys;
}
else {
return new Collection<TKey>(this.Select(this.GetKeyForItem).ToArray());
}
}
}
【问题讨论】:
-
与您的确切问题无关,但总的来说 KeyedCollections 可能会更有效。看到这个相关的stackoverflow.com/questions/2154461/…问题
标签: c# data-structures dictionary hashtable keyedcollection