我正在寻找一种与泛型字典的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());
}
}
}