[英]What is the most efficient way to obtain the list of keys from a KeyedCollection?
I am looking for a way that is as efficient as the Keys property (of type KeyCollection) of a generic dictionary.我正在寻找一种与通用字典的 Keys 属性(KeyCollection 类型)一样有效的方法。
Using a Linq select statement would work, but it would iterate over the whole collection each time the keys are requested, while I believe the keys may already be stored internally.使用 Linq select 语句会起作用,但是每次请求密钥时它都会遍历整个集合,而我相信密钥可能已经存储在内部。
Currently my GenericKeyedCollection class looks like this:目前我的 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();
}
}
}
Update: Thanks to your answers, I will therefore use the following property instead of iterating with Linq.更新:感谢您的回答,因此我将使用以下属性而不是使用 Linq 进行迭代。
public ICollection<TKey> Keys {
get {
if (this.Dictionary != null) {
return this.Dictionary.Keys;
}
else {
return new Collection<TKey>(this.Select(this.GetKeyForItem).ToArray());
}
}
}
As per the documentation , the class has a property, Dictionary , so you can do this:根据文档, class 有一个属性Dictionary ,所以你可以这样做:
var keys = collection.Dictionary.Keys;
Note that there is a caveat, as described in the documentation.请注意,如文档中所述,有一个警告。 If you construct the collection with a threshold value for the dictionary, the dictionary will not be populated until at least that many values has been put into the collection.如果您使用字典的阈值构造集合,则在至少将那么多值放入集合之前,不会填充字典。
If this is not the case for your situation, ie.如果您的情况不是这种情况,即。 the dictionary is always good to go, the above code should do the trick.字典对 go 总是很好,上面的代码应该可以解决问题。
If not, then you either have to change your construction to avoid setting that threshold, or you will just have to loop and extract the key through the GetKeyForItem method.如果不是,那么您要么必须更改构造以避免设置该阈值,要么只需循环并通过GetKeyForItem方法提取密钥。
Not sure this is the most efficient but you could use the Dictionary property to retrieve the generic dictionary representation and then use the the Keys property on that to get the list of keys.不确定这是最有效的,但您可以使用 Dictionary 属性来检索通用字典表示,然后使用其上的 Keys 属性来获取键列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.