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

后端 未结 11 2055
盖世英雄少女心
盖世英雄少女心 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:16

    With LINQ, and using C# (I don't know VB much these days):

    bool b = listOfStrings.Any(s=>myString.Contains(s));
    

    or (shorter and more efficient, but arguably less clear):

    bool b = listOfStrings.Any(myString.Contains);
    

    If you were testing equality, it would be worth looking at HashSet etc, but this won't help with partial matches unless you split it into fragments and add an order of complexity.


    update: if you really mean "StartsWith", then you could sort the list and place it into an array ; then use Array.BinarySearch to find each item - check by lookup to see if it is a full or partial match.

提交回复
热议问题