I am looking for a way that is as efficient as the Keys property (of type KeyCollection) of a generic dictionary.
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.
Currently my GenericKeyedCollection class looks like this:
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.
public ICollection<TKey> Keys {
get {
if (this.Dictionary != null) {
return this.Dictionary.Keys;
}
else {
return new Collection<TKey>(this.Select(this.GetKeyForItem).ToArray());
}
}
}