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

Erw*_*yer 3 c# dictionary hashtable keyedcollection data-structures

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

更新:感谢您的回答,我将使用以下属性而不是使用Linq进行迭代.

    public ICollection<TKey> Keys {
        get {
            if (this.Dictionary != null) {
                return this.Dictionary.Keys;
            }
            else {
                return new Collection<TKey>(this.Select(this.GetKeyForItem).ToArray());
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

ang*_*son 5

根据文档,该类有一个属性Dictionary,所以你可以这样做:

var keys = collection.Dictionary.Keys;
Run Code Online (Sandbox Code Playgroud)

请注意,有一个警告,如文档中所述.如果使用字典的阈值构造集合,则在至少将许多值放入集合之前,不会填充字典.

如果情况不是这样,即.字典总是很好,上面的代码应该可以做到.

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