LINQ對象

LINQ到Objects提供任何LINQ查詢支持的IEnumerable訪問內存中的數據集合,而不需要任何LINQ提供程序(API)的情況下,使用LINQ到SQL或LINQ到XML。

LINQ到對象簡介

查詢在LINQ到對象返回IEnumerable只有類型的變量。 總之,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

使用LINQ到內存中的對象集合查詢

C#

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(); } } }

VB

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.