SHOEISHA iD

※旧SEメンバーシップ会員の方は、同じ登録情報(メールアドレス&パスワード)でログインいただけます

CodeZine編集部では、現場で活躍するデベロッパーをスターにするためのカンファレンス「Developers Summit」や、エンジニアの生きざまをブーストするためのイベント「Developers Boost」など、さまざまなカンファレンスを企画・運営しています。

japan.internet.com翻訳記事

統合言語クエリ(LINQ/Language Integrated Query)入門

LINQのクエリ式を利用する

  • X ポスト
  • このエントリーをはてなブックマークに追加

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までご連絡ください。

この記事は参考になりましたか?

  • X ポスト
  • このエントリーをはてなブックマークに追加
japan.internet.com翻訳記事連載記事一覧

もっと読む

この記事の著者

japan.internet.com(ジャパンインターネットコム)

japan.internet.com は、1999年9月にオープンした、日本初のネットビジネス専門ニュースサイト。月間2億以上のページビューを誇る米国 Jupitermedia Corporation (Nasdaq: JUPM) のニュースサイト internet.comEarthWeb.com からの最新記事を日本語に翻訳して掲載するとともに、日本独自のネットビジネス関連記事やレポートを配信。

※プロフィールは、執筆時点、または直近の記事の寄稿時点での内容です

Mark Strawmyer(Mark Strawmyer)

 大企業および中規模企業向け.NETアプリケーションの開発に携わるシニアアーキテクト。インディアナ州インディアナポリスにあるCrowe Chizekでテクノロジリーダーを務め、Microsoftのソリューションをベースとしたアーキテクチャ、設計および開発を専門とする。C#によるアプリケーション開発で、Microsoft MVPに5年連続で選出されるという栄誉を手にした。連絡先はmstrawmyer@crowechizek.com

※プロフィールは、執筆時点、または直近の記事の寄稿時点での内容です

この記事は参考になりましたか?

この記事をシェア

  • X ポスト
  • このエントリーをはてなブックマークに追加
CodeZine(コードジン)
https://codezine.jp/article/detail/3025 2008/10/02 14:00

おすすめ

アクセスランキング

アクセスランキング

イベント

CodeZine編集部では、現場で活躍するデベロッパーをスターにするためのカンファレンス「Developers Summit」や、エンジニアの生きざまをブーストするためのイベント「Developers Boost」など、さまざまなカンファレンスを企画・運営しています。

新規会員登録無料のご案内

  • ・全ての過去記事が閲覧できます
  • ・会員限定メルマガを受信できます

メールバックナンバー

アクセスランキング

アクセスランキング