加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 01:45:38 所属栏目:百科 来源:网络整理
导读:我正在寻找一种与泛型字典的Keys属性(类型为KeyCollection)一样高效的方法. 使用Linq select语句可以工作,但每次请求密钥时它都会迭代整个集合,而我相信密钥可能已经在内部存储. 目前我的GenericKeyedCollection类看起来像这样: public class GenericKeyedC
我正在寻找一种与泛型字典的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());
            }
        }
    }

解决方法

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

var keys = collection.Dictionary.Keys;

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读