如何:在查詢中傳回元素屬性的子集 (C# 程式設計指南)

如果下列兩個條件都成立,請在查詢運算式中使用匿名型別:

  • 您只要傳回每個來源項目的部分屬性。

  • 您不需要儲存執行查詢所在之方法範圍外的查詢結果。

如果您只要從每個來源項目傳回一個屬性或欄位,只要在 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# 主控台應用程式。

另請參閱