📅  最后修改于: 2020-11-21 07:07:18             🧑  作者: Mango
LINQ to Objects可以使用支持IEnumerable
LINQ to Objects中的查询仅返回通常为IEnumerable
与传统的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;
编译并执行上述代码后,将产生以下结果-
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 departments = 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();
}
}
}
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.