问题描述
对于以下代码块:
For I = 0 To listOfStrings.Count - 1
If myString.Contains(lstOfStrings.Item(I)) Then
Return True
End If
Next
Return False
输出为:
案例 1:
myString: C:Filesmyfile.doc
listOfString: C:Files, C:Files2
Result: True
情况 2:
myString: C:Files3myfile.doc
listOfString: C:Files, C:Files2
Result: False
列表 (listOfStrings) 可能包含多个项目(最少 20 个),并且必须针对数千个字符串(如 myString)进行检查.
The list (listOfStrings) may contain several items (minimum 20) and it has to be checked against a thousands of strings (like myString).
有没有更好(更有效)的方式来编写这段代码?
Is there a better (more efficient) way to write this code?
推荐答案
使用 LINQ,并使用 C#(我现在不太了解 VB):
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);
如果您正在测试相等性,则值得查看 HashSet
等,但这对部分匹配没有帮助,除非您将其拆分为片段并添加复杂度.
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.
更新:如果您的意思是StartsWith",那么您可以对列表进行排序并将其放入数组中;然后使用 Array.BinarySearch
查找每个项目 - 通过查找检查它是完全匹配还是部分匹配.
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.
这篇关于检查字符串是否包含列表(字符串)中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!