如何在查詢中回傳元素屬性的子集(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);  

正在編譯程式碼

要執行此程式碼,將類別複製並貼上到 C# 主控台應用程式,並附上 using System.Linq 指令。

另請參閱