Check if a string contains an element from a list (of strings)

后端 未结 11 1992
盖世英雄少女心
盖世英雄少女心 2020-11-27 11:09

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         


        
相关标签:
11条回答
  • 2020-11-27 11:32

    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))
    
    0 讨论(0)
  • 2020-11-27 11:33

    when you construct yours strings it should be like this

    bool inact = new string[] { "SUSPENDARE", "DIZOLVARE" }.Any(s=>stare.Contains(s));
    
    0 讨论(0)
  • 2020-11-27 11:34
    myList.Any(myString.Contains);
    
    0 讨论(0)
  • 2020-11-27 11:37

    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.

    0 讨论(0)
  • 2020-11-27 11:37

    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))
    
    0 讨论(0)
提交回复
热议问题