检查字符串是否包含来自列表(字符串)的元素 - 是否有更好的方式来编写此代码? [英] To check if a string contains an element from a list (of strings) - Is there a better way to write this code?
问题描述
对于以下代码块:
对于I = 0到listOfStrings.Count - 1
如果myString .Contains(lstOfStrings.Item(I))then
返回True
结束如果
下一个
返回False
输出为:
案例1:
myString:C:\Files\myfile.doc
listOfString:C:\Files\,C:\Files2\\ \\
结果:True
案例2:
$ b
myString:C:\Files3\myfile.doc
listOfString:C:\Files\,C:\ Files2 \
结果:False
在任何时候,列表(listOfStrings) 20),它必须检查数千个字符串(如myString)。
有更好的(更高效的)写这个代码的方式吗?
使用LINQ和使用C#(我现在不知道VB):
bool b = listOfStrings.Any(s => myString.Contains(s));
或(更短更高效,但可以说不太清楚):
bool b = listOfStrings.Any(myString.Contains);
如果你测试平等,那么值得看看 HashSet
等,但是这不会帮助部分匹配,除非你将它拆分成碎片并添加一个复杂的顺序。
update:如果你真的意思是StartsWith,那么你可以对列表排序并将其放入数组;然后使用 Array.BinarySearch
查找每个项目 - 通过查找检查以查看它是完全匹配还是部分匹配。
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
Return False
The output is:
Case 1:
myString: C:\Files\myfile.doc
listOfString: C:\Files\, C:\Files2\
Result: True
Case 2:
myString: C:\Files3\myfile.doc
listOfString: C:\Files\, C:\Files2\
Result: False
At any time 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?
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.
这篇关于检查字符串是否包含来自列表(字符串)的元素 - 是否有更好的方式来编写此代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!