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

后端 未结 12 1089
日久生厌
日久生厌 2020-11-28 05:26

I have this string array:

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

I would like to

12条回答
  •  清酒与你
    2020-11-28 06:08

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

提交回复
热议问题