.NET 2
string[] myStrings = GetMyStrings();
string test = "testValue";
How can I verify if myStrings contains test?
You can use the includes() method in JavaScript to check if an item exists in an array. You can also use it to check if a substring exists within a string. It returns true if the item is found in the array/string and false if the item doesn't exist.
Answer: Yes. Just like arrays can hold other data types like char, int, float, arrays can also hold strings. In this case, the array becomes an array of 'array of characters' as the string can be viewed as a sequence or array of characters.
contains() method in Java is used to check whether or not a list contains a specific element. To check if an element is in an array, we first need to convert the array into an ArrayList using the asList() method and then apply the same contains() method to it.
For primitive values, use the array. includes() method to check if an array contains a value. For objects, use the isEqual() helper function to compare objects and array. some() method to check if the array contains the object.
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); }
);
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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With