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

后端 未结 12 1073
日久生厌
日久生厌 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:15

    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));
    
    0 讨论(0)
  • 2020-11-28 06:15
    string[] strArray = { "text1", "text2", "text3", "text4" };
    string value = "text3";
    
    if(Array.contains(strArray , value))
    {
        // Do something if the value is available in Array.
    }
    
    0 讨论(0)
  • 2020-11-28 06:17

    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
    }
    
    0 讨论(0)
  • 2020-11-28 06:21
    var index = Array.FindIndex(stringArray, x => x == value)
    
    0 讨论(0)
  • 2020-11-28 06:23
    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 讨论(0)
  • 2020-11-28 06:25

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

    0 讨论(0)
提交回复
热议问题