For the following block of code:
For I = 0 To listOfStrings.Count - 1
If myString.Contains(lstOfStrings.Item(I)) Then
Return True
End If
Next
Old question. But since VB.NET
was the original requirement. Using the same values of the accepted answer:
listOfStrings.Any(Function(s) myString.Contains(s))
when you construct yours strings it should be like this
bool inact = new string[] { "SUSPENDARE", "DIZOLVARE" }.Any(s=>stare.Contains(s));
myList.Any(myString.Contains);
Based on your patterns one improvement would be to change to using StartsWith instead of Contains. StartsWith need only iterate through each string until it finds the first mismatch instead of having to restart the search at every character position when it finds one.
Also, based on your patterns, it looks like you may be able to extract the first part of the path for myString, then reverse the comparison -- looking for the starting path of myString in the list of strings rather than the other way around.
string[] pathComponents = myString.Split( Path.DirectorySeparatorChar );
string startPath = pathComponents[0] + Path.DirectorySeparatorChar;
return listOfStrings.Contains( startPath );
EDIT: This would be even faster using the HashSet idea @Marc Gravell mentions since you could change Contains
to ContainsKey
and the lookup would be O(1) instead of O(N). You would have to make sure that the paths match exactly. Note that this is not a general solution as is @Marc Gravell's but is tailored to your examples.
Sorry for the C# example. I haven't had enough coffee to translate to VB.
The drawback of Contains
method is that it doesn't allow to specify comparison type which is often important when comparing strings. It is always culture-sensitive and case-sensitive. So I think the answer of WhoIsRich is valuable, I just want to show a simpler alternative:
listOfStrings.Any(s => s.Equals(myString, StringComparison.OrdinalIgnoreCase))