使用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             //使用傳統fori循環統計
17             int wordCounts = 0;
18             for (int i = 0; i < source.Length; i++)
19             {
20                 if (source[i].ToLowerInvariant()==searchTerm.ToLowerInvariant())
21                 {
22                     wordCounts += 1;
23                 }
24             }
25             //使用LINQ語句查詢統計
26             var matchQuery = from word in source
27                              where word.ToUpperInvariant() == searchTerm.ToUpperInvariant()
28                              select word;
29             int wordCount = matchQuery.Count();
30             Console.WriteLine("{0} occurrences(s) of the search term \"{1}\" were found.", wordCounts, searchTerm);
31             Console.WriteLine("{0} occurrences(s) of the search term \"{1}\" were found.",wordCount,searchTerm);
32             Console.ReadKey();
33         }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM