我正在尋找一種與通用字典的Keys屬性(類型爲KeyCollection)一樣高效的方法。從KeyedCollection獲取密鑰列表的最有效方法是什麼?
使用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可以TAD更有效。見讀取屬性是此相關http://stackoverflow.com/questions/2154461/is-there-a-better-data-structure-than-dictionary-if-the-values-are-objects-and-a問題 – nawfal