방법: 지정된 단어 집합이 들어 있는 문장 쿼리(LINQ)
업데이트: 2007년 11월
이 예제에서는 지정한 단어 집합 각각에 대해 일치하는 내용이 포함된 문장을 텍스트 파일에서 찾는 방법을 보여 줍니다. 검색어의 배열은 이 예제에 하드 코드되어 있지만 런타임에 동적으로 채울 수도 있습니다. 이 예제에서 쿼리는 "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 runtime
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
class FindSentences
{
static void Main()
{
string text = @"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.
string[] sentences = text.Split(new char[] { '.', '?', '!' });
// Define the search terms. This list could also be dynamically populated at runtime.
string[] wordsToMatch = { "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.
var 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. Note that you can explicitly type
// the iteration variable here even though sentenceQuery
// was implicitly typed.
foreach (string str in sentenceQuery)
{
Console.WriteLine(str);
}
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
}
/* Output:
Historically, the world of data and the world of objects have not been well integrated
*/
먼저 텍스트를 문장으로 분할한 다음 문장을 각 단어를 포함하는 문자열 배열로 분할하여 쿼리가 작동합니다. 이러한 배열 각각에 대해 Distinct 메서드는 모든 중복 단어를 제거한 다음 쿼리는 단어 배열 및 wordstoMatch 배열에서 Intersect 연산을 수행합니다. 교집합의 개수가 wordsToMatch 배열의 개수와 같은 경우 모든 단어를 해당 단어에서 찾고 원래 문장이 반환됩니다.
Split 호출 시 문자열에서 문장 부호를 제거하기 위해 이를 구분 기호로 사용합니다. 이렇게 하지 않은 경우 wordsToMatch 배열에서 "Historically"과 일치하지 않는 "Historically," 문자열을 가질 수 있습니다. 소스 텍스트에서 찾은 문장 부호 형식에 따라 추가 구분 기호를 사용해야 할 수도 있습니다.
코드 컴파일
.NET Framework 버전 3.5를 대상으로 하는 Visual Studio 프로젝트를 만듭니다. 기본적으로 프로젝트에는 System.Core.dll에 대한 참조 및 System.Linq 네임스페이스에 대한 using 지시문(C#) 또는 Imports 문(Visual Basic)이 있습니다. C# 프로젝트에서는 System.IO 네임스페이스에 대한 using 지시문을 추가합니다.
프로젝트에 이 코드를 복사합니다.
F5 키를 눌러 프로그램을 컴파일하고 실행합니다.
아무 키나 눌러 콘솔 창을 닫습니다.