string array.Contains?

前端 未结 10 1443
无人及你
无人及你 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 04:02

    I assume you want to check if any elements in your array contains a certain value (test). If so you want to construct a simple loop. In fact I think you should click here.

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

    Here's a .NET 2.0 compliant approach. Using Array.Find will return null if the value isn't found.

    C# Approach

    string[] myStrings = { "A", "B", "testValue" };
    string test = "testValue";
    string result = Array.Find(myStrings, delegate(string s) { return s == test; });
    Console.WriteLine("Result: " + result);
    

    If you need a case insensitive match use s.Equals(test, StringComparison.InvariantCultureIgnoreCase).

    EDIT: with VB.NET 2.0 more effort is required since it doesn't support anonymous delegates. Instead you would need to add a Function and use AddressOf to point to it. You would need to set the testValue as a member or property since it will not be passed in to the predicate method. In the following example I use Array.Exists.

    VB.NET Approach

    ' field or property ' 
    Dim test As String = "testValue"
    
    Sub Main
        Dim myStrings As String() = { "A", "B", "testValue" }       
        Dim result As Boolean = Array.Exists(myStrings, AddressOf ContainsValue)
        Console.WriteLine(result)
    End Sub
    
    ' Predicate method '
    Private Function ContainsValue(s As String) As Boolean
        Return s = test
    End Function
    
    0 讨论(0)
  • 2021-02-07 04:08

    In .NET 2.0, you could do the following if you want the index:

    int index = Array.FindIndex(
        myStrings,
        delegate(string s) { return s.Equals(test); }
    );
    

    index will be -1 if myStrings does not contain test.

    If you merely want to check for existence:

    bool exists = Array.Exists(
        myStrings,
        delegate(string s) { return s.Equals(test); }
    );
    
    0 讨论(0)
  • 2021-02-07 04:10

    Thought I would add another to the mix, first available in .NET 3.5, I believe:

    Enumerable.Contains(myStrings.ToArray(), test)
    
    0 讨论(0)
提交回复
热议问题