MoShe
MoShe

Reputation: 6427

Checking if a string array contains a value, and if so, getting its position

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?

Upvotes: 202

Views: 545028

Answers (13)

Erhan Urun
Erhan Urun

Reputation: 279

Use System.Linq

stringArray.Contains(value3);

Upvotes: 8

Taran
Taran

Reputation: 3221

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

Upvotes: 50

Mayer Spitz
Mayer Spitz

Reputation: 2525

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

Upvotes: 0

james31rock
james31rock

Reputation: 2705

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
}

Upvotes: 0

user5248404
user5248404

Reputation: 1

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

}

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

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
}

Upvotes: 380

Jaydeep Bhatt
Jaydeep Bhatt

Reputation: 11

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

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

Upvotes: -3

pKami
pKami

Reputation: 354

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.

Upvotes: 4

Priyank Gajera
Priyank Gajera

Reputation: 19

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

Upvotes: -4

BLUEPIXY
BLUEPIXY

Reputation: 40145

var index = Array.FindIndex(stringArray, x => x == value)

Upvotes: 85

Glory Raj
Glory Raj

Reputation: 17691

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

Upvotes: 5

Jon Skeet
Jon Skeet

Reputation: 1499750

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

Upvotes: 15

BrokenGlass
BrokenGlass

Reputation: 160852

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

Upvotes: 6

Related Questions