繁体   English   中英

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

[英]What is the most efficient way to obtain the list of keys from a KeyedCollection?

我正在寻找一种与通用字典的 Keys 属性(KeyCollection 类型)一样有效的方法。

使用 Linq select 语句会起作用,但是每次请求密钥时它都会遍历整个集合,而我相信密钥可能已经存储在内部。

目前我的 GenericKeyedCollection class 看起来像这样:

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());
            }
        }
    }

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

var keys = collection.Dictionary.Keys;

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

如果您的情况不是这种情况,即。 字典对 go 总是很好,上面的代码应该可以解决问题。

如果不是,那么您要么必须更改构造以避免设置该阈值,要么只需循环并通过GetKeyForItem方法提取密钥。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM