简体   繁体   中英

Finding an index of an element in a string array

I have done a search for finding an index of an element in a string array on this forum. The solutions that I found uses the following method:

Array.IndexOf

I'm new to C# and I haven't heard of this method yet. I can find an index for integers. However I struggling to find a solutions for string type arrays.

Here is the code I use to find the index for integers:

public int Search(int testValue)
{
    int i = 0;
    while(i < test.Length && testValue != test[i])
        i++;
    if(i == test.Length)
        i = -1;
    return i;
}

How do I modify the above to be able to use for string type array, or is there another simply method that will do the trick?

I think, you need following example. Let me know, if you need other example or looking for other solution.

string[] vals = { "val1", "val2" ,"val3"};
int idx = Array.IndexOf(vals, "val2");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM