linq可以对多种数据源和对象进行查询,如数据库、数据集、XML文档、数组等。
通过对linq的使用,可以减少代码量并优化检索操作。
LINQ关键字
from 指定数据源和范围变量
where 根据布尔表达式(由逻辑与 或 等组成)从数据源中筛选元素
select 指定查询结果中的元素所具有的类型或表现形式
group 对对查询结果按照键值进行分组
into 提供一个标示符,它可以充当对 join group 或 select 子句结果的引用
orderby 对查询出的元素进行排序
join 按照两个指定匹配条件来联接俩个数据源
let 产生一个用于查询表达式中子表达式查询结果的范围变量
下面介绍一个上课时的例子:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 第六次__1 { public class Customer { public string FirstName { get; set; } public string LastName { get; set; } public string EmailAddress { get; set; } // Overrides the Object.ToString() to provide a // string representation of the object properties. public override string ToString() { return string.Format("{0} {1} Email: {2}", FirstName, LastName, EmailAddress); } } // Create a customer list with sample data public class Tester { private static List<Customer> CreateCustomerList() { List<Customer> customers = new List<Customer> { new Customer { FirstName = "Orlando",LastName = "Gee", EmailAddress = "orlando0@adventure-works.com"}, new Customer { FirstName = "Keith", LastName = "Harris", EmailAddress = "keith0@adventure-works.com" }, new Customer { FirstName = "Donna", LastName = "Carreras", EmailAddress = "donna0@adventure-works.com" }, new Customer { FirstName = "Janet", LastName = "Gates", EmailAddress = "janet1@adventure-works.com" }, new Customer { FirstName = "Lucy", LastName = "Harrington", EmailAddress = "lucy0@adventure-works.com" } }; return customers; } static void Main() // Main program { List<Customer> customers = CreateCustomerList(); IEnumerable<Customer> result = from customer in customers where customer.FirstName == "Donna" select customer; Console.WriteLine("FirstName == "Donna""); foreach (Customer customer in result) { Console.WriteLine(customer.ToString()); } customers[3].FirstName = "Donna"; Console.WriteLine("FirstName == "Donna" (take two)"); foreach (Customer customer in result) { Console.WriteLine(customer.ToString()); } Console.ReadLine(); } } }
程序运行的结果为:
首先我们创建了一个customer类,并在这给类的基础上增加了一些数据(有点想一个小型的数据库),并在主函数中查询
这些类容。
对于主函数:
static void Main() // Main program { List<Customer> customers = CreateCustomerList(); IEnumerable<Customer> result = from customer in customers where customer.FirstName == "Donna" select customer; Console.WriteLine("FirstName == "Donna""); foreach (Customer customer in result) { Console.WriteLine(customer.ToString()); } customers[3].FirstName = "Donna"; Console.WriteLine("FirstName == "Donna" (take two)"); foreach (Customer customer in result) { Console.WriteLine(customer.ToString()); } Console.ReadLine(); }
首先查询了 customer.FirstName == "Donna" 的内容,并将结果输出。(这些查询语句跟数据库的查询语句差不多,学过数据库的理解起来应该很轻松)。
var这个关键字是用来声明一个隐藏类型的
我们可以用var来声明一个没有类型的变量。(这并不是表明变量没有类型,而是C#会自动识别变量的类型。)
ordering关键字则是用来给数据库中的内容进行排序以进行一些特殊的查找。
如:
orderby customer.LastName, address.Street descending
结果的集合将先以customer.LastName升序排列,再在此基础上以address.Street降序排列。