クエリで要素のプロパティのサブセットを返す方法 (C# プログラミング ガイド)

次の両方の条件に当てはまる場合は、クエリ式に匿名型を使用します。

  • 各ソース要素のプロパティの一部のみを返したい。

  • クエリを実行したメソッドのスコープ外のクエリ結果を保存する必要がない。

各ソース要素の 1 つのプロパティまたはフィールドのみを返す場合は、select 句でドット演算子 (.) を使用します。 たとえば、各 studentID のみを返すには、次のように select 句を記述します。

select student.ID;  

次に、匿名型を使用して、各ソース要素のプロパティのうち、指定した条件に一致するプロパティのみを返す例を示します。

private static void QueryByScore()
{
    // Create the query. var is required because
    // the query produces a sequence of anonymous types.
    var queryHighScores =
        from student in students
        where student.ExamScores[0] > 95
        select new { student.FirstName, student.LastName };

    // Execute the query.
    foreach (var obj in queryHighScores)
    {
        // The anonymous type's properties were not named. Therefore
        // they have the same names as the Student properties.
        Console.WriteLine(obj.FirstName + ", " + obj.LastName);
    }
}
/* Output:
Adams, Terry
Fakhouri, Fadi
Garcia, Cesar
Omelchenko, Svetlana
Zabokritski, Eugene
*/

名前を指定しない場合、匿名型にはプロパティのソース要素名が使用されます。 匿名型のプロパティに新しい名前を付けるには、次のように select ステートメントを記述します。

select new { First = student.FirstName, Last = student.LastName };  

前の例でこの方法を試すには、Console.WriteLine ステートメントも次のように変更する必要があります。

Console.WriteLine(student.First + " " + student.Last);  

コードのコンパイル

このコードを実行するには、クラスをコピーし、System.Linq に using ディレクティブを使用した C# コンソール アプリケーションに貼り付けます。

関連項目