Is string in array?

C#ArraysString

C# Problem Overview


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;
}

C# Solutions


Solution 1 - C#

Just use the already built-in Contains() method:

using System.Linq;

//...

string[] array = { "foo", "bar" };
if (array.Contains("foo")) {
	//...
}

Solution 2 - C#

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.

Solution 3 - C#

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).

Solution 4 - C#

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));

Solution 5 - C#

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.

Solution 6 - C#

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.

Solution 7 - C#

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

Solution 8 - C#

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.

Solution 9 - C#

This is quicker than iterating through the array manually:

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

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

Solution 10 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBradView Question on Stackoverflow
Solution 1 - C#Dave MarkleView Answer on Stackoverflow
Solution 2 - C#Gabriel McAdamsView Answer on Stackoverflow
Solution 3 - C#NoldorinView Answer on Stackoverflow
Solution 4 - C#user1228View Answer on Stackoverflow
Solution 5 - C#Andrew HareView Answer on Stackoverflow
Solution 6 - C#Zack ElanView Answer on Stackoverflow
Solution 7 - C#DaveView Answer on Stackoverflow
Solution 8 - C#masfenixView Answer on Stackoverflow
Solution 9 - C#Chris BallanceView Answer on Stackoverflow
Solution 10 - C#mateiasuView Answer on Stackoverflow