LINQ到Objects提供任何LINQ查詢支援的IEnumerable<T>存取記憶體中的資料集合,而不需要任何LINQ提供程式(API)的情況下,使用LINQ到SQL或LINQ到XML。
查詢在LINQ到物件返回IEnumerable<T>只有型別的變數。 總之,LINQ到Objects在早期提供了一種新方法到集合,它需要寫很長程式碼換成宣告性程式碼的集合,清楚地描述了所需的資料編碼(foreach迴圈複雜得多)進行資料檢索至所需關鍵的檢索。
LINQ有許多優勢超過傳統的foreach迴圈,更易讀,強大的過濾,分組的能力,增強排序以最小的應用程式的編碼物件。這樣LINQ查詢在性質上也更加緊湊,並且移植到任何其它資料源沒有任何修改或只需稍加修改。
下面是一個簡單的LINQ到物件的例子:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LINQtoObjects { class Program { static void Main(string[] args) { string[] tools = { "Tablesaw", "Bandsaw", "Planer", "Jointer", "Drill", "Sander" }; var list = from t in tools select t; StringBuilder sb = new StringBuilder(); foreach (string s in list) { sb.Append(s + Environment.NewLine); } Console.WriteLine(sb.ToString(), "Tools"); Console.ReadLine(); } } }
在這個例子中,字串(工具)的陣列被用作物件的集合,使用LINQ到物件進行查詢。
Objects query is: var list = from t in tools select t;
當上述程式碼被編譯和執行時,它產生了以下結果:
Tablesaw Bandsaw Planer Jointer Drill Sander
using System; using System.Collections.Generic; using System.Linq; namespace LINQtoObjects { class Department { public int DepartmentId { get; set; } public string Name { get; set; } } class LinqToObjects { static void Main(string[] args) { List<Department> departments = new List<Department>(); departments.Add(new Department { DepartmentId = 1, Name = "Account" }); departments.Add(new Department { DepartmentId = 2, Name = "Sales" }); departments.Add(new Department { DepartmentId = 3, Name = "Marketing" }); var departmentList = from d in departments select d; foreach (var dept in departmentList) { Console.WriteLine("Department Id = {0} , Department Name = {1}", dept.DepartmentId, dept.Name); } Console.WriteLine("\nPress any key to continue."); Console.ReadKey(); } } }
Imports System.Collections.Generic Imports System.Linq Module Module1 Sub Main(ByVal args As String()) Dim account As New Department With {.Name = "Account", .DepartmentId = 1} Dim sales As New Department With {.Name = "Sales", .DepartmentId = 2} Dim marketing As New Department With {.Name = "Marketing", .DepartmentId = 3} Dim departments As New System.Collections.Generic.List(Of Department)(New Department() {account, sales, marketing}) Dim departmentList = From d In departments For Each dept In departmentList Console.WriteLine("Department Id = {0} , Department Name = {1}", dept.DepartmentId, dept.Name) Next Console.WriteLine(vbLf & "Press any key to continue.") Console.ReadKey() End Sub Class Department Public Property Name As String Public Property DepartmentId As Integer End Class End Module
當C#或VB的上述程式碼被編譯和執行時,它產生了以下結果:
Department Id = 1, Department Name = Account Department Id = 2, Department Name = Sales Department Id = 3, Department Name = Marketing Press any key to continue.