string array.Contains?

2020-02-09 06:52发布

.NET 2

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

How can I verify if myStrings contains test?

10条回答
我欲成王,谁敢阻挡
2楼-- · 2020-02-09 07:28

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
查看更多
Viruses.
3楼-- · 2020-02-09 07:29

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.

查看更多
Viruses.
4楼-- · 2020-02-09 07:31

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

查看更多
可以哭但决不认输i
5楼-- · 2020-02-09 07:32

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

List<string> myStrings = new List<string>(GetMyStrings());
if(myStrings.Contains("testValue"))
{
    // Do Work
}
查看更多
登录 后发表回答