I need a list of strings and a way to quickly determine if a string is contained within that list.
To enhance lookup speed, I considered SortedList
and
If you're on .NET 3.5 or higher, use HashSet<String>.
Failing that, a Dictionary<string, byte>
(or whatever type you want for the TValue
type parameter) would be faster than a SortedList
if you have a lot of entries - the latter will use a binary search, so it'll be O(log n) lookup, instead of O(1).
If you feel like rolling your own data structure, use a Trie. http://en.wikipedia.org/wiki/Trie
worst-case is if the string is present: O(length of string)
HashSet<string> is like a Dictionary
, but with only keys.
I know the question is old as hell, but I just had to solve the same problem, only for a very small set of strings(between 2 and 4).
In my case, I actually used manual lookup over an array of strings which turned up to be much faster than HashSet<string>
(I benchmarked it).
for (int i = 0; i < this.propertiesToIgnore.Length; i++)
{
if (this.propertiesToIgnore[i].Equals(propertyName))
{
return true;
}
}
Note, that it is better than hash set for only for tiny arrays!
EDIT: works only with a manual for
loop, do not use LINQ, details in comments
This sounds like a job for
var keys = new HashSet<string>();
Per MSDN: The Contains function has O(1) complexity.
But you should be aware that it does not give an error for duplicates when adding.
If you just want to know if a string is in the set use HashSet<string>