Search code examples
c#.netlistdictionary.net-2.0

Pass Dictionary KeyCollection mainaining the access speed


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.


Solution

  • In a comment, you mention that your intent here is .Contains(). In that case, what you are looking for is HashSet<T>, which does exactly that - it just holds keys (no values), and provides fast Contains checks. So; for your Dictionary<long,object> you could do something like:

    var set = new HashSet<long>(dictionary.Keys);
    

    and pass that over. For convenience, HashSet<T> implements ICollection<T> (if you want to scope it to an interface, rather than the concrete type) - this has a Contains too.

    Actually, it may be more efficient to use (which also works on .NET 2.0):

    ICollection<long> = dictionary.Keys;
    

    and pass that; the implementation of Contains(key) on this is O(1), since it is implemented via:

    bool ICollection<TKey>.Contains(TKey item)
    {
        return this.dictionary.ContainsKey(item);
    }