[c#] Is string in array?

What would be the best way to look in a string[] to see if it contains a element. This was my first shot at it. But perhaps there is something that I am overlooking. The array size will be no larger than 200 elements.

bool isStringInArray(string[] strArray, string key)
{
    for (int i = 0; i <= strArray.Length - 1; i++)
        if (strArray[i] == key)
            return true;
    return false;
}

This question is related to c# arrays string

The answer is


Linq (for s&g's):

var test = "This is the string I'm looking for";
var found = strArray.Any(x=>x == test);

or, depending on requirements

var found = strArray.Any(
    x=>x.Equals(test, StringComparison.OrdinalIgnoreCase));

You can also use LINQ to iterate over the array. or you can use the Find method which takes a delegate to search for it. However I think the find method is a bit more expensive then just looping through.


As mentioned many times in the thread above, it's dependent on the framework in use. .Net Framework 3 and above has the .Contains() or Exists() methods for arrays. For other frameworks below, can do the following trick instead of looping through array...

((IList<string>)"Your String Array Here").Contains("Your Search String Here")

Not too sure on efficiency... Dave


Is the array sorted? If so you could do a binary search. Here is the .NET implementation as well. If the array is sorted then a binary search will improve performance over any iterative solution.


Arrays are, in general, a poor data structure to use if you want to ask if a particular object is in the collection or not.

If you'll be running this search frequently, it might be worth it to use a Dictionary<string, something> rather than an array. Lookups in a Dictionary are O(1) (constant-time), while searching through the array is O(N) (takes time proportional to the length of the array).

Even if the array is only 200 items at most, if you do a lot of these searches, the Dictionary will likely be faster.


Linq (for s&g's):

var test = "This is the string I'm looking for";
var found = strArray.Any(x=>x == test);

or, depending on requirements

var found = strArray.Any(
    x=>x.Equals(test, StringComparison.OrdinalIgnoreCase));

Arrays are, in general, a poor data structure to use if you want to ask if a particular object is in the collection or not.

If you'll be running this search frequently, it might be worth it to use a Dictionary<string, something> rather than an array. Lookups in a Dictionary are O(1) (constant-time), while searching through the array is O(N) (takes time proportional to the length of the array).

Even if the array is only 200 items at most, if you do a lot of these searches, the Dictionary will likely be faster.


You're simply after the Array.Exists function (or the Contains extension method if you're using .NET 3.5, which is slightly more convenient).


This is quicker than iterating through the array manually:

static bool isStringInArray(string[] strArray, string key)
    {

        if (strArray.Contains(key))
            return true;
        return false;
    }

You're simply after the Array.Exists function (or the Contains extension method if you're using .NET 3.5, which is slightly more convenient).


Linq (for s&g's):

var test = "This is the string I'm looking for";
var found = strArray.Any(x=>x == test);

or, depending on requirements

var found = strArray.Any(
    x=>x.Equals(test, StringComparison.OrdinalIgnoreCase));

Is the array sorted? If so you could do a binary search. Here is the .NET implementation as well. If the array is sorted then a binary search will improve performance over any iterative solution.


You're simply after the Array.Exists function (or the Contains extension method if you're using .NET 3.5, which is slightly more convenient).


As mentioned many times in the thread above, it's dependent on the framework in use. .Net Framework 3 and above has the .Contains() or Exists() methods for arrays. For other frameworks below, can do the following trick instead of looping through array...

((IList<string>)"Your String Array Here").Contains("Your Search String Here")

Not too sure on efficiency... Dave


Linq (for s&g's):

var test = "This is the string I'm looking for";
var found = strArray.Any(x=>x == test);

or, depending on requirements

var found = strArray.Any(
    x=>x.Equals(test, StringComparison.OrdinalIgnoreCase));

Is the array sorted? If so you could do a binary search. Here is the .NET implementation as well. If the array is sorted then a binary search will improve performance over any iterative solution.


If you don't want to or simply can't use Linq you can also use the static Array.Exists(...); function:

https://msdn.microsoft.com/en-us/library/yw84x8be%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396

var arr = new string[]{"bird","foo","cat","dog"};

var catInside = Array.Exists( 
  arr, // your Array
  (s)=>{ return s == "cat"; } // the Predicate
);

When the Predicate do return true once catInside will be true as well.


You can also use LINQ to iterate over the array. or you can use the Find method which takes a delegate to search for it. However I think the find method is a bit more expensive then just looping through.


This is quicker than iterating through the array manually:

static bool isStringInArray(string[] strArray, string key)
    {

        if (strArray.Contains(key))
            return true;
        return false;
    }

Is the array sorted? If so you could do a binary search. Here is the .NET implementation as well. If the array is sorted then a binary search will improve performance over any iterative solution.


If you don't want to or simply can't use Linq you can also use the static Array.Exists(...); function:

https://msdn.microsoft.com/en-us/library/yw84x8be%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396

var arr = new string[]{"bird","foo","cat","dog"};

var catInside = Array.Exists( 
  arr, // your Array
  (s)=>{ return s == "cat"; } // the Predicate
);

When the Predicate do return true once catInside will be true as well.


Arrays are, in general, a poor data structure to use if you want to ask if a particular object is in the collection or not.

If you'll be running this search frequently, it might be worth it to use a Dictionary<string, something> rather than an array. Lookups in a Dictionary are O(1) (constant-time), while searching through the array is O(N) (takes time proportional to the length of the array).

Even if the array is only 200 items at most, if you do a lot of these searches, the Dictionary will likely be faster.


I know this is old, but I wanted the new readers to know that there is a new method to do this using generics and extension methods.

You can read my blog post to see more information about how to do this, but the main idea is this:

By adding this extension method to your code:

public static bool IsIn<T>(this T source, params T[] values)
{
    return values.Contains(source);
}

you can perform your search like this:

string myStr = "str3"; 
bool found = myStr.IsIn("str1", "str2", "str3", "str4");

It works on any type (as long as you create a good equals method). Any value type for sure.


Arrays are, in general, a poor data structure to use if you want to ask if a particular object is in the collection or not.

If you'll be running this search frequently, it might be worth it to use a Dictionary<string, something> rather than an array. Lookups in a Dictionary are O(1) (constant-time), while searching through the array is O(N) (takes time proportional to the length of the array).

Even if the array is only 200 items at most, if you do a lot of these searches, the Dictionary will likely be faster.


I know this is old, but I wanted the new readers to know that there is a new method to do this using generics and extension methods.

You can read my blog post to see more information about how to do this, but the main idea is this:

By adding this extension method to your code:

public static bool IsIn<T>(this T source, params T[] values)
{
    return values.Contains(source);
}

you can perform your search like this:

string myStr = "str3"; 
bool found = myStr.IsIn("str1", "str2", "str3", "str4");

It works on any type (as long as you create a good equals method). Any value type for sure.


This is quicker than iterating through the array manually:

static bool isStringInArray(string[] strArray, string key)
    {

        if (strArray.Contains(key))
            return true;
        return false;
    }

You can also use LINQ to iterate over the array. or you can use the Find method which takes a delegate to search for it. However I think the find method is a bit more expensive then just looping through.