Luciano
Luciano

Reputation: 2999

Best lookup data structure to store only the keys (Dictionary without value)

What is the best data structure in .Net with high performance lookup, like a binary tree implementation, but to store only the keys (string keys) ?

We need only to check if a certain key is present in the collection. Like:

Dictonary<string, object> myKeys;
myKeys.Add("key1", null);
myKeys.Add("key2", null);
// Dozens or hundreds keys

Assert.IsTrue(myKeys.Contains("key1")); 

Upvotes: 5

Views: 5984

Answers (1)

Mitch Wheat
Mitch Wheat

Reputation: 300559

A HashSet (in System.Collections.Generic):

HashSet is an unordered collection containing unique elements. It has the standard collection operations Add, Remove, Contains, but since it uses a hash-based implementation, these operation are O(1).

e.g.

    HashSet<int> evenNumbers = new HashSet<int>();
    HashSet<int> oddNumbers = new HashSet<int>();

    for (int i = 0; i < 5; i++)
    {
        // Populate numbers with just even numbers.
        evenNumbers.Add(i * 2);

        // Populate oddNumbers with just odd numbers.
        oddNumbers.Add((i * 2) + 1);
    }

    if (evenNumbers.Contains(2))
    {
        Console.WriteLine("2 is even.");
    }

Upvotes: 17

Related Questions