LINQ to Objects提供了支持IEnumerable< T>的任何LINQ查询的用法,用于访问内存数据集合,而无需LINQ to SQL或LINQ to XML的LINQ提供程序(API).
LINQ to Objects简介
LINQ to Objects中的查询返回类型通常为IEnumerable的变量< T>只要.简而言之,LINQ to Objects为早期的集合提供了一种全新的方法,编写用于从集合中检索数据的长编码(更复杂的循环)至关重要,现在可以通过编写清楚描述所需数据的声明性代码来替换它.需要检索.
与传统的foreach循环相比,LINQ to Objects还有许多优点,例如更高的可读性,强大的过滤功能,分组功能,增强的排序和最少的应用程序编码.这样的LINQ查询本质上也更紧凑,可以移植到任何其他数据源而无需任何修改或只需稍加修改.
下面是一个简单的LINQ to Objects示例 :
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 to Objects查询的对象.
Objects query is:var list = from t in tools select t;
编译并执行上述代码时,会产生以下结果 :
TablesawBandsawPlanerJointerDrillSander
查询在内存集合中使用LINQ to Objects
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) { Listdepartments = new List (); 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.GenericImports System.LinqModule 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 = AccountDepartment Id = 2, Department Name = SalesDepartment Id = 3, Department Name = MarketingPress any key to continue.