深入理解C#(四)

*第一章(大致了解C#各个版本的特性:LINQ简介)

LINQ简介

LINQ(Language Integrated Query,语言集成查询)
用于简化查询

查询表达式和进程内查询

例子:
查询所有供应商和对应产品,先连接产品和供应商,再按价格筛选,然后按先供应商名再产品名的优先级排序,最后打印每个供应商名称和产品名称

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
List<ProductWithSupplierID> products = ProductWithSupplierID.GetSampleProducts();
List<Supplier> suppliers = Supplier.GetSampleSuppliers();
var filtered = from p in products
join s in suppliers on p.SupplierID equals s.SupplierID
where p.Price > 10
orderby s.Name, p.Name
select new
{
SupplierName = s.Name,
ProductName = p.Name
};
foreach (var v in filtered)
{
Console.WriteLine("Supplier={0}; Product={1}",v.SupplierName, v.ProductName);
}

特性:隐式类型局部变量(implicitly typed local variable)

使用var关键字说明,编译器根据变量的初始值推断其类型

LINQ to XML

例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
XDocument doc = XDocument.Load("data.xml");
var filtered = from p in doc.Descendants("Product")
join s in doc.Descendants("Supplier")
on (int)p.Attribute("SupplierID")
equals (int)s.Attribute("SupplierID")
where (decimal)p.Attribute("Price") > 10
orderby (string)s.Attribute("Name"),
(string)p.Attribute("Name")
select new
{
SupplierName = (string)s.Attribute("Name"),
ProductName = (string)p.Attribute("Name")
};
foreach (var v in filtered)
{
Console.WriteLine("Supplier={0}; Product={1}",
v.SupplierName, v.ProductName);
}
}

LINQ to SQL

例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using (LinqDemoDataContext db = new LinqDemoDataContext())
{
var filtered = from p in db.Products
join s in db.Suppliers
on p.SupplierID equals s.SupplierID
where p.Price > 10
orderby s.Name, p.Name
select new
{
SupplierName = s.Name,
ProductName = p.Name
};
foreach (var v in filtered)
{
Console.WriteLine("Supplier={0}; Product={1}",
v.SupplierName, v.ProductName);
}
}

虽然查询是用C#代码来表示的,但却是用SQL执行。
实际发出一个数据库请求,被转化为SQL查询。