一般的な辞書の (KeyCollection 型の) Keys プロパティと同じくらい効率的な方法を探しています。
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());
}
}
}