【问题标题】:What is the most efficient way to obtain the list of keys from a KeyedCollection?从 KeyedCollection 获取键列表的最有效方法是什么?
【发布时间】:2011-10-08 02:58:17
【问题描述】:

我正在寻找一种与通用字典的 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();
        }
    }
}

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

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

【问题讨论】:

标签: c# data-structures dictionary hashtable keyedcollection


【解决方案1】:

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

var keys = collection.Dictionary.Keys;

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

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 读取该属性是一个 O(1) 操作。
    猜你喜欢
    • 2017-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-05
    • 1970-01-01
    相关资源
    最近更新 更多