194

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?

Leigh
  • 28,765
  • 10
  • 55
  • 103
MoShe
  • 6,197
  • 17
  • 51
  • 77

13 Answers13

373

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
}
Niklas
  • 13,005
  • 23
  • 79
  • 119
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 1
    ...And I've been using foreach for months. BTW is this computationally faster than BLUEPIXY's answer? Or slower? – Max von Hippel Aug 10 '15 at 19:11
  • 2
    Does `Array.IndexOf` care about capitalization? Does `"text1" == "TEXT1"`? – E.V.I.L. Apr 28 '17 at 01:11
  • 1
    `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` – benscabbia Oct 28 '17 at 17:08
  • 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](https://stackoverflow.com/questions/8935161/how-to-add-a-case-insensitive-option-to-array-indexof) – Kyle Oct 09 '19 at 09:00
83
var index = Array.FindIndex(stringArray, x => x == value)
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
46

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"));
Matthias Braun
  • 32,039
  • 22
  • 142
  • 171
Taran
  • 2,895
  • 25
  • 22
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...)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • how do I find the possition of the world in the array using Contains? – MoShe Oct 23 '11 at 16:20
  • Is there a possiblity to check a string item in string array A exists in another string array B? – Murali Murugesan Apr 02 '14 at 14:04
  • @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.) – Jon Skeet Apr 02 '14 at 14:08
  • I was trying to answer here http://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 :) – Murali Murugesan Apr 02 '14 at 14:10
  • @MuraliMurugesan: Well that sounds like `if (months.Contains(model.Month))` – Jon Skeet Apr 02 '14 at 14:13
  • Thanks a lot. I used `model.contains(months[x])` based on your input – Murali Murugesan Apr 02 '14 at 14:16
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);
BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
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.

pKami
  • 359
  • 2
  • 8
4

Use System.Linq

stringArray.Contains(value3);
Erhan Urun
  • 228
  • 3
  • 9
  • 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](https://stackoverflow.com/help/how-to-answer). – moken Jul 14 '23 at 11:28
4

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));
Glory Raj
  • 17,397
  • 27
  • 100
  • 203
1

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");
            }
Mayer Spitz
  • 2,577
  • 1
  • 20
  • 26
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); }

}
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
}
james31rock
  • 2,615
  • 2
  • 20
  • 25
-3
string[] strArray = { "text1", "text2", "text3", "text4" };
string value = "text3";

if(Array.contains(strArray , value))
{
    // Do something if the value is available in Array.
}
-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.
}
  • 3
    The question was about finding the position of an item in an array.... With the `Contains` method you don't have this information – Bidou Jun 11 '13 at 06:08