203

I have this string array:

string[] stringArray = { "text1", "text2", "text3", "text4" };
string value = "text3";

I would like to determine if stringArray contains value. If so, I want to locate its position in the array.

I don't want to use loops. Can anyone suggest how I might do this?

13 Answers 13

382

You could use the Array.IndexOf method:

string[] stringArray = { "text1", "text2", "text3", "text4" };
string value = "text3";
int pos = Array.IndexOf(stringArray, value);
if (pos > -1)
{
    // the array contains the string and the pos variable
    // will have its position in the array
}
Sign up to request clarification or add additional context in comments.

4 Comments

...And I've been using foreach for months. BTW is this computationally faster than BLUEPIXY's answer? Or slower?
Does Array.IndexOf care about capitalization? Does "text1" == "TEXT1"?
Array.IndexOf returns −1 only if the index is 0-bounded. This case would break, so be aware! var a = Array.CreateInstance(typeof(int),new int[] { 2 }, new int[] { 1 }); a.SetValue(1, 1); Console.WriteLine(Array.IndexOf(a, 26)); // 0
This is useful if you're looking for an exact match. However, this might be useful if you don't care about case: How to add a case-insensitive option to Array.IndexOf
85
var index = Array.FindIndex(stringArray, x => x == value)

4 Comments

This should be the accepted answer because it allows one to pass in a lambda to do more complicated things like Array.FindIndex(array, x => x.StartsWith("insert string here"))
But that is not what the question is asking for. The question asks how do you find a known value from an array.
@KarlGjertsen I want to locate its position in the array
This is very useful though, being able to do something like an x.ToUpper() was pretty beneficial to me.
50

We can also use Exists:

string[] array = { "cat", "dog", "perl" };

// Use Array.Exists in different ways.
bool a = Array.Exists(array, element => element == "perl");
bool c = Array.Exists(array, element => element.StartsWith("d"));
bool d = Array.Exists(array, element => element.StartsWith("x"));

3 Comments

Clean and simple answer
How do I check individual values? When I tried checking a char array for a char, I got a message that char can't be converted to System.Predicate<char>
Array.Exists(array, element => element.Equals("perl", StringComparison.OrdinalIgnoreCase) If you're concerned with caps.
15

EDIT: I hadn't noticed you needed the position as well. You can't use IndexOf directly on a value of an array type, because it's implemented explicitly. However, you can use:

IList<string> arrayAsList = (IList<string>) stringArray;
int index = arrayAsList.IndexOf(value);
if (index != -1)
{
    ...
}

(This is similar to calling Array.IndexOf as per Darin's answer - just an alternative approach. It's not clear to me why IList<T>.IndexOf is implemented explicitly in arrays, but never mind...)

6 Comments

how do I find the possition of the world in the array using Contains?
Is there a possiblity to check a string item in string array A exists in another string array B?
@MuraliMurugesan: It's not clear what you're asking - whether the two arrays have any items in common? One specific item? (In the latter case, the fact that it's also in an array is irrelevant.)
I was trying to answer here stackoverflow.com/a/22812525/1559213 . I struck up to return true/false for Html.CheckBox line. Actually there is a months array and also the model which has some months. If Model month is present in months array we need to return true. Thanks for rocket response :)
@MuraliMurugesan: Well that sounds like if (months.Contains(model.Month))
|
9

Use System.Linq

stringArray.Contains(value3);

1 Comment

Answer needs supporting information Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
6

You can use Array.IndexOf() - note that it will return -1 if the element has not been found and you have to handle this case.

int index = Array.IndexOf(stringArray, value);

Comments

5

you can try like this...you can use Array.IndexOf() , if you want to know the position also

       string [] arr = {"One","Two","Three"};
       var target = "One";
       var results = Array.FindAll(arr, s => s.Equals(target));

Comments

4

IMO the best way to check if an array contains a given value is to use System.Collections.Generic.IList<T>.Contains(T item) method the following way:

((IList<string>)stringArray).Contains(value)

Complete code sample:

string[] stringArray = { "text1", "text2", "text3", "text4" };
string value = "text3";
if (((IList<string>)stringArray).Contains(value)) Console.WriteLine("The array contains "+value);
else Console.WriteLine("The given string was not found in array.");

T[] arrays privately implement a few methods of List<T>, such as Count and Contains. Because it's an explicit (private) implementation, you won't be able to use these methods without casting the array first. This doesn't only work for strings - you can use this trick to check if an array of any type contains any element, as long as the element's class implements IComparable.

Keep in mind not all IList<T> methods work this way. Trying to use IList<T>'s Add method on an array will fail.

3 Comments

Yours is basically the same answer as Priyank's. It doesn't give the index of the element which is what the OP was asking for.
@reggaeguitar Agree with you there!
It's the solution I was looking for, even though it doesn't completely answer the question.
0
string x ="Hi ,World";
string y = x;
char[] whitespace = new char[]{ ' ',\t'};          
string[] fooArray = y.Split(whitespace);  // now you have an array of 3 strings
y = String.Join(" ", fooArray);
string[] target = { "Hi", "World", "VW_Slep" };

for (int i = 0; i < target.Length; i++)
{
    string v = target[i];
    string results = Array.Find(fooArray, element => element.StartsWith(v, StringComparison.Ordinal));
    //
    if (results != null)
    { MessageBox.Show(results); }

}

Comments

0

I created an extension method for re-use.

   public static bool InArray(this string str, string[] values)
    {
        if (Array.IndexOf(values, str) > -1)
            return true;

        return false;
    }

How to call it:

string[] stringArray = { "text1", "text2", "text3", "text4" };
string value = "text3";
if(value.InArray(stringArray))
{
  //do something
}

1 Comment

Where is the position that the OP is asking for?
0

You can try this, it looks up for the index containing this element, and it sets the index number as the int, then it checks if the int is greater then -1, so if it's 0 or more, then it means it found such an index - as arrays are 0 based.

string[] Selection = {"First", "Second", "Third", "Fourth"};
string Valid = "Third";    // You can change this to a Console.ReadLine() to 
    //use user input 
int temp = Array.IndexOf(Selection, Valid); // it gets the index of 'Valid', 
                // in our case it's "Third"
            if (temp > -1)
                Console.WriteLine("Valid selection");
            }
            else
            {
                Console.WriteLine("Not a valid selection");
            }

Comments

-3
string[] strArray = { "text1", "text2", "text3", "text4" };
string value = "text3";

if(Array.contains(strArray , value))
{
    // Do something if the value is available in Array.
}

1 Comment

It gives error: 'System.Array' does not contain a definition for 'contains'.
-4

The simplest and shorter method would be the following.

string[] stringArray = { "text1", "text2", "text3", "text4" };
string value = "text3";

if(stringArray.Contains(value))
{
    // Do something if the value is available in Array.
}

1 Comment

The question was about finding the position of an item in an array.... With the Contains method you don't have this information

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.