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.cs182 chars10 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.cs131 chars9 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