方法 : 文字列での単語の出現回数をカウントする (LINQ)
更新 : 2007 年 11 月
この例では、LINQ クエリを使用して、指定された単語が文字列内に出現する回数をカウントする方法を示します。カウントを実行するには、まず Split メソッドを呼び出して単語の配列を作成します。Split メソッドは、パフォーマンスの低下につながります。文字列に対して単語のカウント以外の操作を行わない場合は、代わりに Matches メソッドまたは IndexOf メソッドの使用を検討することをお勧めします。ただし、パフォーマンスが重要な問題ではない場合や、他の種類のクエリを実行する目的で既に文章を分割した場合は、LINQ を使用して単語や語句をカウントすることにも意味があります。
使用例
Class CountWords
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."
Dim searchTerm As String = "data"
' Convert the string into an array of words.
Dim dataSource As String() = text.Split(New Char() {" ", ",", ".", ";", ":"}, _
StringSplitOptions.RemoveEmptyEntries)
' Create and execute the query. It executes immediately
' because a singleton value is produced.
' Use ToLower to match "data" and "Data"
Dim matchQuery = From word In dataSource _
Where word.ToLowerInvariant() = searchTerm.ToLowerInvariant() _
Select word
' Count the matches.
Dim count As Integer = matchQuery.Count()
Console.WriteLine(count & " occurrence(s) of the search term """ & _
searchTerm & """ were found.")
' Keep console window open in debug mode.
Console.WriteLine("Press any key to exit.")
Console.ReadKey()
End Sub
End Class
' Output:
' 3 occurrence(s) of the search term "data" were found.
class CountWords
{
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.";
string searchTerm = "data";
//Convert the string into an array of words
string[] source = text.Split(new char[] { '.', '?', '!', ' ', ';', ':', ',' }, StringSplitOptions.RemoveEmptyEntries);
// Create and execute the query. It executes immediately
// because a singleton value is produced.
// Use ToLowerInvariant to match "data" and "Data"
var matchQuery = from word in source
where word.ToLowerInvariant() == searchTerm.ToLowerInvariant()
select word;
// Count the matches.
int wordCount = matchQuery.Count();
Console.WriteLine("{0} occurrences(s) of the search term \"{1}\" were found.", wordCount, searchTerm);
// Keep console window open in debug mode
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
}
/* Output:
3 occurrences(s) of the search term "data" were found.
*/
コードのコンパイル方法
.NET Framework Version 3.5 を対象とする Visual Studio プロジェクトを作成します。プロジェクトには、System.Core.dll への参照と、System.Linq 名前空間に対する using ディレクティブ (C#) または Imports ステートメント (Visual Basic) が既定で含まれます。C# プロジェクトでは、System.IO 名前空間に対する using ディレクティブを追加します。
このコードをプロジェクト内にコピーします。
F5 キーを押して、プログラムをコンパイルおよび実行します。
任意のキーを押して、コンソール ウィンドウを終了します。