I am getting back a "string[]" from a 3rd party library. I want to do a contains on it. what is the most efficient way of doing this?
6 Answers
If you are only checking a single time, use Array.IndexOf or the LINQ Contains method like Marc proposed. If you are checking several times, it might be faster to first convert the string array into a HashSet<string>.
1 Comment
Unless you know the String array is sorted by a particular order the most efficient thing you can do is linear algorithm (i.e. compare each string in the array until you find a match or the end of the array.
If the array is sorted a binary search is much faster.
Another way to optimize the algorithm (although the complexity is not reduced) is to vectorize the string comparisons.
Comments
You can use the IEnumerable.Foreach Custom Extension
public static class CollectionExtensions
{
public static void ForEach<T>(this IEnumerable list, Action<T> action)
{
foreach (T item in list)
{
action(item);
}
}
}
class Program
{
static void Main(string[] args)
{
String[] list = new String[] { "Word1", "Word2", "Word3" };
list.ForEach<String>(p => Console.WriteLine(p));
list.ForEach(delegate(String p) { Console.WriteLine(p); });
}
}
Hope this help's.