string array.Contains?

前端 未结 10 1434
无人及你
无人及你 2021-02-07 03:22

.NET 2

string[] myStrings = GetMyStrings();    
string test = \"testValue\";

How can I verify if myStrings contains test

相关标签:
10条回答
  • 2021-02-07 03:50

    I have found an elegant answer at the page here http://www.dotnettoad.com/index.php?/archives/10-Array.Contains.html. What you have to do in .NET 2.0 is to cast to IList and call Contains method.

    (IList<string> mystrings).Contains(test);
    
    0 讨论(0)
  • 2021-02-07 03:51

    How about this:

    Sub Main
        Dim myStrings(4) As String
        myStrings(0) = "String 1"
        myStrings(1) = "String 2"
        myStrings(2) = "testValue"
        myStrings(3) = "String 3"
        myStrings(4) = "String 4"
    
        Dim test As String = "testValue"
    
        Dim isFound As Boolean = Array.IndexOf(myStrings, test) >= 0
    
        If isFound Then
            Console.WriteLine("Found it!")
        End If
    End Sub
    

    This should work for .Net 2.0 and VB.Net.

    0 讨论(0)
  • 2021-02-07 03:53
    bool ContainsString(string[] arr, string testval)
    {
        if ( arr == null )
            return false;
        for ( int i = arr.Length-1; i >= 0; i-- )
            if ( arr[i] == testval )
                return true;
        return false;
    }
    

    And this will have the best performance ever. :P

    0 讨论(0)
  • 2021-02-07 03:55

    Here is almost the exact same question on msdn. Find String in String Array As others have said you really have two options: 1) Use a list for easier checking 2) Loop through your array to find the string

    0 讨论(0)
  • 2021-02-07 04:00

    you can use Array.BinarySearch as described below.

     string[] strArray = GetStringArray();
            string strToSearch ="test";
            Array.BinarySearch(strArray, strToSearch);
    
    0 讨论(0)
  • 2021-02-07 04:01

    Instead of using a static array, you could use a List:

    List<string> myStrings = new List<string>(GetMyStrings());
    if(myStrings.Contains("testValue"))
    {
        // Do Work
    }
    
    0 讨论(0)
提交回复
热议问题