1. 程式人生 > 實用技巧 >使用C# LINQ 查詢字串中某個詞出現的次數

使用C# LINQ 查詢字串中某個詞出現的次數

 1 public static void CountWords()
 2         {   
3 string text = @"Historically, the world of data and the world of objects" + 4 @" have not been well integrated. Programmers work in C# or Visual Basic" + 5 @" and also in SQL or XQuery. On the one side are concepts such as classes,
" + 6 @" objects, fields, inheritance, and .NET Framework APIs. On the other side" + 7 @" are tables, columns, rows, nodes, and separate languages for dealing with" + 8 @" them. Data types often require translation between the two worlds; there are" + 9 @"
different standard functions. Because the object world has no notion of query, a" + 10 @" query can only be represented as a string without compile-time type checking or" + 11 @" IntelliSense support in the IDE. Transferring data from SQL tables or XML trees to" + 12 @"
objects in memory is often tedious and error-prone."; 13 string searchTerm = "data"; 14 string[] source = text.Split(new char[] { '.', '?', '!', ' ', ';', ':', ',' }, 15 StringSplitOptions.RemoveEmptyEntries); 16 var matchQuery = from word in source 17 where word.ToUpperInvariant() == searchTerm.ToUpperInvariant() 18 select word; 19 int wordCount = matchQuery.Count(); 20 Console.WriteLine("{0} occurrences(s) of the search term \"{1}\" were found.",wordCount,searchTerm); 21 Console.ReadKey(); 22 23 }