如何解决如果字符串在VB.NET中使用LINQ,如果字符串包含字符串数组中的任何项目,如何返回True
我在堆栈溢出时找不到此问题,但如果在这里,请告诉我,我将其清除。
在VB.NET中使用LINQ,如果字符串包含字符串数组中的一项,如何返回True?
这是多行代码。您如何在VB.NET中使用LINQ做到这一点?
Sub Main
Dim endPointTimeoutText As Array = {"endpoint timeout","endpoint is not available"}
Dim strResult As String = "endpoint is not available sample text."
Dim booleanResult As Boolean = False
For Each item As String In endPointTimeoutText
If strResult.Contains(item) Then
booleanResult = True
Exit For
End If
Next
Console.WriteLine(booleanResult) 'Only included this for the example
End Sub
取决于字符串(strResult)是否包含字符串数组(endPointTimeoutText)中的值之一,预期结果为“真”或“假”
解决方法
您会在头脑上转过头来-不要问“对于这个字符串X,该数组中的哪些内容在该字符串中”,您会询问“对于此字符串数组,其中的哪些内容在该字符串中X“:
Dim whichStringsArePresent = endPointTimeoutText.Where(Function(ett) strResult.Contains(ett))
Dim firstImeoutStringFound = endPointTimeoutText.FirstOrDefault(Function(ett) strResult.Contains(ett))
Dim wasATimeout = endPointTimeoutText.Any(Function(ett) strResult.Contains(ett))
等
顺便说一下,如果这样做,它将使您的代码更加美观,从而使事物集合具有复数名称。考虑更多类似这样的东西:
Dim wasATimeout = endPointTimeoutTexts.Any(Function(ett) strResult.Contains(ett))
它很微妙,但在可读性方面很重要
,感谢Caius Jard在此方面的帮助。我将针对下面要用作答案的内容发布完整的程序。
我需要使用列表而不是数组,以便可以使用'Any()'方法。再次感谢Caius,我非常感谢!
Sub Main
Dim endPointTimeoutText As String = "endpoint timeout,endpoint is not available"
Dim endPointTimeoutList As New List(Of String)
Dim strResult As String = "endpoint is not available sample text."
endPointTimeoutList = endPointTimeoutText.Split(",").ToList()
Dim areAnyStringsPresent As Boolean
areAnyStringsPresent = endPointTimeoutList.Any(Function(itemInEndPointTimeoutList) strResult.Contains(itemInEndPointTimeoutList))
Console.WriteLine(areAnyStringsPresent)
'This code produces the following output:
'True
End Sub
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。