121

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

10 Answers 10

240

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

using System.Linq;

//...

string[] array = { "foo", "bar" };
if (array.Contains("foo")) {
    //...
}
Sign up to request clarification or add additional context in comments.

4 Comments

For some reason when I first looked for the method I couldn't find it...thanks.
@Brad: That's because its an extension method coming from Enumerable.
As a one-liner: (new string[] { "foo", "bar" }).Contains("foo")
Even shorter: new[] { "foo", "bar" }.Contains(foo)
28

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.

3 Comments

I have something like this var xxx = csvData.Rows[0].ItemArray[0].IsIn(".00", "0.0", ".25", "0.5", ".5", ".50", ".75"); what I want to do is look through the who datatable in the first column to see if the values do not end in any of the following strings.. if they don't then I want to return a string stating that it's missing a value .00 for example using your example I can't seem to get this one to work it's a bit trickier since I do not want to return a bool I altered your method to return a string but still doesn't work any suggestions
This seems better posed as a question on the site. Go ahead and reference this answer if needed.
I was actually able to come up with an awesome way to do what I was wanting to do I wrote something that would check if values of a string inside of a for loop for Datatables ItemArray, end with any of the following values I had in my string public static bool EndWithValue(this string value, IEnumerable<string> values) { return values.Any(item => value.EndsWith(item)); }
12

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

1 Comment

Here is a working example for .NET 2.0: if (Array.Exists(arrayToLookThrough, o => o == elementToSearchFor))
9

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

Comments

6

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.

Comments

2

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.

1 Comment

binary-search is O(log n); dictionary subtends to O(1) - but there is a lot of overhead; for small-to-mid-size, linear search or binary search can out-perform.
2

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

Comments

1

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.

1 Comment

The Find method will be algorithmically identical to the "looping-through" method. Any extra expense will be some object creation and maybe a layer or two of indirection but, if you're worrying about optimizing those out at the expense of readability, you're worrying about the wrong things.
1

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.

Comments

0

This is quicker than iterating through the array manually:

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

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

2 Comments

using LINQ is faster than iterating through the string as was done in the example. strArray.Contains(key) is all that is really necessary
Behind the scenes, strArray.Contains(key) is just going to loop through the array anyway... there's no magic involved that gets you out of doing an O(n) search.

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.