英文:
Trying to find subset of string in a list of string
问题
我正在尝试在vb.net中的字符串列表中查找子字符串。我不明白为什么在查看了很多这里和其他地方的信息后,这不起作用。我在下面写了一个简单的例子。我觉得我应该能够使用通配符,但似乎没有什么能奏效的。
子 主(args As 字符串())
Dim 字符串列表 作为 新的 列表(Of 字符串) 从 {"book1", "book2", "book3"}
Dim st 作为 字符串 = 字符串列表(0)
'这段代码可以工作
如果 st.包含("book") 那么
控制台.写线("这个可以工作!")
控制台.读线()
否则
控制台.写线("这个不起作用!")
控制台.读线()
结束 如果
'这段代码不起作用
如果 字符串列表.包含("book") 那么
控制台.写线("这个可以工作!")
控制台.读线()
否则
控制台.写线("这个不起作用!")
控制台.读线()
结束 如果
结束 子
我尝试使用通配符。我觉得除了遍历列表之外,应该有一个更好的解决方案。
英文:
I'm trying to find a substring in a list of string in vb.net. I'm not understanding why this doesn't work after lots of looking around on here and other places. I wrote a simple example below. I feel like I should be able to use a wild card but nothing seems to do the trick.
Sub Main(args As String())
Dim StringList As New List(Of String) From {"book1", "book2", "book3"}
Dim st As String = StringList(0)
'this block of code works
If st.Contains("book") Then
Console.WriteLine("This works!")
Console.ReadLine()
Else
Console.WriteLine("This doesn't work!")
Console.ReadLine()
End If
'this block of code does not work
If StringList.Contains("book") Then
Console.WriteLine("This works!")
Console.ReadLine()
Else
Console.WriteLine("This doesn't work!")
Console.ReadLine()
End If
End Sub
I tried using a wild card. I feel like there is a better solution than iterating through the list.
答案1
得分: 3
我觉得有比遍历列表更好的解决方案。
这确实是需要发生的事情。但是,你可以使用 .Any() 函数,并传递一个 Lambda,它会为你执行迭代:
If StringList.Any(Function(s) s.Contains("book")) Then
Console.WriteLine("这个有效!")
Else
Console.WriteLine("这个无效!")
End If
英文:
> I feel like there is a better solution than iterating through the
> list.
Well, that really is what needs to happen. You can, however, use the .Any() function and pass it a Lambda, and it will do the iterating for you:
If StringList.Any(Function(s) s.Contains("book")) Then
Console.WriteLine("This works!")
Else
Console.WriteLine("This doesn't work!")
End If
答案2
得分: 0
Idle_Mind的答案似乎是正确的;你必须进行迭代,而编译器可以完成迭代。但我更愿意像这样使用String.Join
:
If String.Join(",", StringList).Contains("book") Then
对我来说,这似乎更清晰,因为它遵循了我的思维方式。
请注意,如果不使用此方法包含分隔符,那么如果有几个字符串紧挨在一起,例如bonobo
和okra
,可能会得到不正确的结果。
我不确定从长远来看哪个速度更快。
英文:
Idle_Mind's answer seems right; you must iterate, and you can have the iteration done by the compiler. But I would rather use String.Join
like this:
If String.Join(",", StringList).Contains("book") Then
It seems clearer to me because of following the way my mind works.
Note that if you don't include the separator with this method then you could get incorrect results, if you had a couple of strings next to each other like bonobo
and okra
.
I'm not sure which would be faster in the long run.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论