LINQを使った簡単な例
基礎知識を押さえたところで、次は簡単な例をいくつか挙げてLINQを実際に動かしてみます。構造体型とファイルからデータを読み込む例と、LINQでイベントログにアクセスする例でLINQの使い方を検討しましょう。
構造体型へのアクセス
構文の紹介のところで使用した例に基づき、構造体型へのクエリを行うサンプルを作成します。Customer
構造体型を作成し、NorthwindデータベースからCustomer
構造体型にデータを格納するコードを記述します。「City」が「Berlin」ではないレコードをすべて選択してから、そのレコードをコンソールに出力します。このサンプルではCustomer
オブジェクトを選択するので、カンマ区切りの属性リストを出力するToString
メソッドをCustomer
クラスに追加します。
using System; using System.Collections.Generic; using System.Linq; namespace LINQIntro { class Customer { public string CustomerName { get; set; } public string ContactName { get; set; } public string City { get; set; } public override string ToString() { return this.CustomerName + ", " + this.ContactName + ", " + this.City; } } class Program { static void Main(string[] args) { Program.ShowCustomers(); } public static void ShowCustomers() { // Build a list of customers using an object initializer List<Customer> customers = new List<Customer> { new Customer { CustomerName = "Alfreds Futterkiste", ContactName = "Maria Anders", City = "Berlin"}, new Customer { CustomerName = "Ana Trujillo Emparedados y helados", ContactName = "Ana Trujillo", City = "Mexico D.F."}, new Customer { CustomerName = "Antonio Moreno Taqueria", ContactName = "Antonio Moreno", City = "Mexico D.F."}, new Customer { CustomerName = "Around the Horn", ContactName = "Thomas Hardy", City = "London"}, new Customer { CustomerName = "Berglunds snabbkop", ContactName = "Christina Berglund", City = "Lulea"}}; // Query the list of customers and select whatever // comes back var customer = from c in customers where c.City != "Berlin" orderby c.ContactName select c; // Display the selected records to the console foreach (var row in customer) { Console.WriteLine(row); } Console.ReadLine(); } } }
ファイルリストの表示
次の例では、LINQを使用してローカルPCのディレクトリを検索し、特定の名前で始まるファイルがあるかどうかを調べます。前の例と同じように、ディレクトリとファイル名は私のコンピュータにあったものから任意に選びました。クエリ文の中のディレクトリとファイル名は、読者の場合にもクエリ文が動作するように修正する必要があります。
using System; using System.Collections.Generic; using System.Linq; namespace LINQIntro { class Program { static void Main(string[] args) { Program.ShowFiles(); } public static void ShowFiles() { // Point to a specific directory System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo( "C:\\Program Files\\Microsoft Visual Studio 9.0"); // Find files in the directory structure and select it var directoryList = from f in dirInfo.GetFiles("*.*", System.IO.SearchOption.AllDirectories) where f.Name.StartsWith("re") select f; // Display the selected records to the console foreach (var row in directoryList) { Console.WriteLine(row); } Console.ReadLine(); } } }
実行中のプロセスの表示
次の例では、ローカルPCで実行されているプロセスのリストをLINQで取得し、そのリストをコンソールに出力します。
using System; using System.Collections.Generic; using System.Linq; namespace LINQIntro { class Program { static void Main(string[] args) { Program.ShowProcesses(); } public static void ShowProcesses() { // Select the list of processes and shape the output var processes = from p in System.Diagnostics.Process.GetProcesses() orderby p.ProcessName select new { p.ProcessName, p.Id, p.WorkingSet64, p.Threads, p.HandleCount }; // Display the selected records to the console foreach (var row in directoryList) { Console.WriteLine(row); } Console.ReadLine(); } } }
アプリケーションイベントログへのアクセス
次の例では、LINQを使用してアプリケーションイベントログからデータを読み込みます。読み込んだイベントログを検索して、特定のメッセージが含まれるエラーがないかどうかを調べます。検索対象のメッセージは、私のローカルPCのイベントログにあったエラーメッセージから任意に選びました。読者の場合にもローカルのイベントログを検索してヒットするように、クエリ文を修正してください。まだLINQの信者ではないとしても、イベントログを操作した経験のある人にとっては、これがLINQの実力と価値を示す格好の例になるはずです。
using System; using System.Collections.Generic; using System.Linq; namespace LINQIntro { class Program { static void Main(string[] args) { Program.ShowEventLog(); } public static void ShowEventLog() { // Attach to the Application Event Log System.Diagnostics.EventLog myLog = new System.Diagnostics.EventLog(); myLog.Log = "Application"; // Query for an error record with "terminated" in the text // You'll want to adjust the EventLogEntryType and message // to find entries in your local event log // Notice how a custom object is being shaped var logEntries = from System.Diagnostics.EventLogEntry e in myLog.Entries where e.EntryType == System.Diagnostics.EventLogEntryType.Error && e.Message.Contains("terminated") select new { e.Source, e.InstanceId, e.Message, e.TimeGenerated }; // Display the selected records to the console foreach (var row in logEntries) { Console.WriteLine(row); } Console.ReadLine(); } } }
まとめ
LINQの概要とLINQに関する誤解について基本的な内容をいくつか紹介し、ベースとなる言語機能の基礎知識を簡単に説明しました。LINQの構文を紹介した後、いくつかの例でLINQを使ってみました。この記事が、LINQの背景となった技術の理解に役立ち、データアクセスにおけるLINQの実力を知っていただく一助になれば幸いです。
今後の予定
次回のコラムでは、LINQ to XMLまたはLINQ to SQLのどちらかを取り上げます。このコラムで特に説明を希望する話題がこの他にあれば、mstrawmyer@crowechizek.comまでご連絡ください。