次の方法で共有


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

両方の条件が適用される場合は、クエリ式で匿名型を使用します。

  • 各ソース要素のプロパティの一部のみを返す必要があります。

  • クエリを実行するメソッドの範囲外にクエリ結果を格納する必要はありません。

各ソース要素から 1 つのプロパティまたはフィールドのみを返す場合は、 select 句でドット演算子を使用できます。 たとえば、各IDstudentのみを返すには、次のように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# コンソール アプリケーションに貼り付けます。

こちらも参照ください