이 예제에서는 지정된 각 단어 집합에 대한 일치 항목이 포함된 텍스트 파일에서 문장을 찾는 방법을 보여 줍니다. 이 예제에서는 검색 용어 배열이 하드 코딩되어 있지만 런타임에 동적으로 채워질 수도 있습니다. 이 예제에서 쿼리는 "Historically", "data" 및 "integrated"라는 단어가 포함된 문장을 반환합니다.
예시
Class FindSentences
Shared Sub Main()
Dim text As String = "Historically, the world of data and the world of objects " &
"have not been well integrated. Programmers work in C# or Visual Basic " &
"and also in SQL or XQuery. On the one side are concepts such as classes, " &
"objects, fields, inheritance, and .NET Framework APIs. On the other side " &
"are tables, columns, rows, nodes, and separate languages for dealing with " &
"them. Data types often require translation between the two worlds; there are " &
"different standard functions. Because the object world has no notion of query, a " &
"query can only be represented as a string without compile-time type checking or " &
"IntelliSense support in the IDE. Transferring data from SQL tables or XML trees to " &
"objects in memory is often tedious and error-prone."
' Split the text block into an array of sentences.
Dim sentences As String() = text.Split(New Char() {".", "?", "!"})
' Define the search terms. This list could also be dynamically populated at run time
Dim wordsToMatch As String() = {"Historically", "data", "integrated"}
' Find sentences that contain all the terms in the wordsToMatch array
' Note that the number of terms to match is not specified at compile time
Dim sentenceQuery = From sentence In sentences
Let w = sentence.Split(New Char() {" ", ",", ".", ";", ":"},
StringSplitOptions.RemoveEmptyEntries)
Where w.Distinct().Intersect(wordsToMatch).Count = wordsToMatch.Count()
Select sentence
' Execute the query
For Each str As String In sentenceQuery
Console.WriteLine(str)
Next
' Keep console window open in debug mode.
Console.WriteLine("Press any key to exit.")
Console.ReadKey()
End Sub
End Class
' Output:
' Historically, the world of data and the world of objects have not been well integrated
쿼리는 먼저 텍스트를 문장으로 분할한 다음 문장을 각 단어를 포함하는 문자열 배열로 분할하여 작동합니다. 각 배열에 대해 Distinct 메서드는 모든 중복 단어를 제거하고, 그런 다음 쿼리가 단어 배열과 Intersect 배열에서 wordsToMatch
작업을 수행합니다. 교집합 수가 배열의 wordsToMatch
개수와 같으면 모든 단어가 단어에서 발견되고 원래 문장이 반환됩니다.
Split 호출에서, 문장 부호는 문자열에서 제거하기 위해 구분 기호로 사용됩니다. 예를 들어, 이 작업을 수행하지 않았다면 wordsToMatch
배열의 "Historically"와 일치하지 않는 문자열 "Historically,"를 사용할 수 있습니다. 원본 텍스트에 있는 문장 부호 유형에 따라 추가 구분 기호를 사용해야 할 수 있습니다.
코드 컴파일
Visual Basic 콘솔 애플리케이션 프로젝트를 만들어서, System.Linq 네임스페이스에 대한 Imports
문을 추가합니다.
참고하십시오
.NET