C# 从KeyedCollection获取密钥列表的最有效方法是什么?

C# 从KeyedCollection获取密钥列表的最有效方法是什么?,c#,data-structures,dictionary,hashtable,keyedcollection,C#,Data Structures,Dictionary,Hashtable,Keyedcollection,我正在寻找一种与泛型字典的Keys属性(KeyCollection类型)一样高效的方法 使用Linq select语句可以工作,但每次请求密钥时,它都会在整个集合中迭代,而我相信密钥可能已经存储在内部 当前,我的GenericKeyedCollection类如下所示: public class GenericKeyedCollection<TKey, TItem> : KeyedCollection<TKey, TItem> { private Func<T

我正在寻找一种与泛型字典的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();
        }
    }
}
公共类GenericKeyedCollection:KeyedCollection{
私有函数getKeyFunc;
受保护的覆盖TKey GetKeyForItem(TItem项目){
返回getKeyFunc(项目);
}
公共GenericKeyedCollection(Func getKeyFunc){
this.getKeyFunc=getKeyFunc;
}
公共列表密钥{
得到{
返回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());
            }
        }
    }
公共i收集密钥{
得到{
if(this.Dictionary!=null){
返回此.Dictionary.Keys;
}
否则{
返回新集合(this.Select(this.GetKeyForItem.ToArray());
}
}
}

不确定这是否是最有效的,但您可以使用Dictionary属性检索通用字典表示,然后使用其上的the Keys属性获取键列表

根据,该类有一个属性,因此您可以执行以下操作:

var keys = collection.Dictionary.Keys;
请注意,有一个警告,如文档中所述。如果使用字典的阈值构造集合,则在至少将这么多值放入集合之前,不会填充字典

如果你的情况不是这样,比如说字典总是很好用的,那么上面的代码应该可以做到这一点


如果没有,则您必须更改构造以避免设置该阈值,或者只需通过该方法循环并提取密钥。

读取该属性是一个O(1)操作。与您的具体问题无关,但通常KeyedCollections可能会更有效。看这个相关的问题