fast look up in collection in csharp

In C#, the fastest way to lookup an item in a collection is by using a Dictionary. Dictionary is a generic collection that stores a key-value pair. You can use the key to look up a value in the dictionary very quickly. Here is an example:

main.cs
var dict = new Dictionary<string, string>();
dict.Add("key1", "value1");
dict.Add("key2", "value2");

string value;
if (dict.TryGetValue("key1", out value))
{
    // use the value
}
182 chars
10 lines

In the example above, we create a dictionary with string keys and values. We add two items to the dictionary, then we use the TryGetValue method to look up the value of the key "key1". This method returns a boolean value indicating whether the key was found in the dictionary, and if it was, the value is returned as an out parameter.

Another option for faster lookups is to use a HashSet if you only need to check if an item is in the collection or not.

main.cs
var set = new HashSet<string>();
set.Add("item1");
set.Add("item2");

if (set.Contains("item1"))
{
    // the item is in the set
}
131 chars
9 lines

In the example above, we create a HashSet with string items, and we add two items to the set. We check if "item1" is in the set using the Contains method, which returns a boolean indicating whether the set contains the item or not.

These collection types have better performance than other collection types such as List or ArrayList for lookups, as they use hashing to lookup values instead of iterating over them. However, they have some limitations, such as the fact that the key must be unique for a Dictionary, and the items in a HashSet must be unique.

gistlibby LogSnag