5

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 6

9

Array.IndexOf:

bool contains = Array.IndexOf(arr, value) >= 0;

Or just use LINQ:

bool contains = arr.Contains(value);

LINQ should be "fast enough" for most purposes.

Sign up to request clarification or add additional context in comments.

Comments

8

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

Good catch with HashSet; +1 ;-p
2

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

1

I'm fairly certain that a for loop is faster, if absolute speed is your concern. I.e.,

for (int i = 0; i < arr.Length; ++i)
  if (arr[i] == value) return true;
return false;

Comments

1

If you're searching once or twice, use a linear search or IndexOf.

If you're searching a few times, put the strings into a HashSet.

If you're searching zillions of times in a time-critical fashion, use a HashSet and manage its bucket count yourself.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.