摘要:[LINQ] LINQ to Object 實例01 (ARRAYLIST)
REF : http://msdn.microsoft.com/zh-tw/library/bb397937.aspx
使用 LINQ 查詢非泛型 IEnumerable 集合 (如 ArrayList) 時,必須明確宣告範圍變數的型別,以反映集合中特定物件的型別。例如,如果您擁有 Student 物件的 ArrayList,則 from 子句 (C#) 或 From 子句 (Visual Basic) 看起來應該如下:
// C# var query = from Student s in arrList ... 'Visual Basic Dim query = From student As Student In arrList _ ...
指定範圍變數的型別,就會將 ArrayList 中的每個項目轉換 (Cast) 為 Student。
在查詢運算式中使用明確指定型別的範圍變數,相當於呼叫 Cast<TResult> 方法。如果無法執行指定的轉換,則 Cast<TResult> 會擲回例外狀況 (Exception)。Cast<TResult> 和 OfType<TResult> 是可以對非泛型 IEnumerable 型別執行的兩個標準查詢運算子方法。
範例
下列範例顯示透過 ArrayList 的簡單查詢。請注意,在程式碼呼叫 Add 方法時,這個範例使用的是物件初始設定式,但這不是必要的。
using System; using System.Collections; using System.Linq; namespace NonGenericLINQ { public class Student { public string FirstName { get; set; } public string LastName { get; set; } public int[] Scores { get; set; } } class Program { static void Main(string[] args) { ArrayList arrList = new ArrayList(); arrList.Add( new Student { FirstName = "Svetlana", LastName = "Omelchenko", Scores = new int[] { 98, 92, 81, 60 } }); arrList.Add( new Student { FirstName = "Claire", LastName = "O’Donnell", Scores = new int[] { 75, 84, 91, 39 } }); arrList.Add( new Student { FirstName = "Sven", LastName = "Mortensen", Scores = new int[] { 88, 94, 65, 91 } }); arrList.Add( new Student { FirstName = "Cesar", LastName = "Garcia", Scores = new int[] { 97, 89, 85, 82 } }); var query = from Student student in arrList where student.Scores[0] > 95 select student; foreach (Student s in query) Console.WriteLine(s.LastName + ": " + s.Scores[0]); // Keep the console window open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); } } } /* Output: Omelchenko: 98 Garcia: 97 */