您的位置:首页 > 其它

学习笔记二--如何:查询包含一组指定单词的句子 (LINQ)

2008-06-24 16:02 561 查看
学习笔记二--如何:查询包含一组指定单词的句子 (LINQ)(来自微软MSDN)

此示例演示如何查找文本文件中包含指定的一组单词中每个单词的匹配项的句子。虽然在此示例中搜索条件数组是硬编码的,但也可以在运行时动态填充此数组。在此示例中,查询返回包含单词“Historically”、“data”和“integrated”的句子。
Visual Basic
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

C#
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 的调用中,使用标点符号作为分隔符,以从字符串中移除标点符号。如果您没有这样做,则假如您有一个字符串“Historically,”,该字符串不会与 wordsToMatch 数组中的“Historically”相匹配。根据源文本中标点的类型,您可能必须使用其他分隔符。
编译代码
· 创建一个面向 .NET Framework 3.5 版的 Visual Studio 项目。默认情况下,该项目具有对 System.Core.dll 的引用,以及 System.Linq 命名空间的 using 指令 (C#) 或 Imports 语句 (Visual Basic)。在 C# 项目中,添加 System.IO 命名空间的 using 指令。
· 将此代码复制到您的项目。
· 按 F5 编译并运行程序。
· 按任意键退出控制台窗口。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐