I have a class that only uses the keyCollection of a Dictionary<long, object>, and I would like to pass to other class only the keys.
I know that the dictionary has a theorical O(1) access-by-index (as a HashTable) but if I convert the keyCollection to a List, the access would change to O(n).
How could I pass the keyCollection to my class maintaining the O(1) access?
Edit: I’m using .NET 2.0.
In a comment, you mention that your intent here is
.Contains(). In that case, what you are looking for isHashSet<T>, which does exactly that – it just holds keys (no values), and provides fastContainschecks. So; for yourDictionary<long,object>you could do something like:and pass that over. For convenience,
HashSet<T>implementsICollection<T>(if you want to scope it to an interface, rather than the concrete type) – this has aContainstoo.Actually, it may be more efficient to use (which also works on .NET 2.0):
and pass that; the implementation of
Contains(key)on this is O(1), since it is implemented via: