文章目录
简介
LINQ有很多,很复杂。可分为很多部分,比如
- LINQ to Objects
- LINQ to SQL
- LINQ to XML
- LINQ to Dataset
- LINQ to Entities
-
本节只介绍LINQ to Objects。
-
有专业的数目介绍LINQ,比如LINQ in action。
LINQ举例
LINQ查询,遍历一个集合
- LINQ的语法,一般是from开头。
- 类似于sql语法。
IEnumerable<Patent> patents = PatentData.Patents;
IEnumerable<Inventor> inventors = PatentData.Inventors;
var query =
from inventor in inventors
select inventor;
// 返回的是Enumerable的类型
Print(query)
where筛选
var query =
from patent in patents
where patent.YearOfPublication.StartsWith("18")
select new { patent Title };
输出文件名及其最后修改时间(LINQ中定义临时变量使用let)
var query =
from filename in Directory.GetFiles("C:/")
let fileinfo = new FileInfo(filename)
select new { fileinfo.Name, fileinfo.LastWriteTime };
orderby排序
var query =
from filename in Directory.GetFiles("C:/")
let fileinfo = new FileInfo(filename)
orderby fileinfo.Length.descending
select new { fileinfo.Name, fileinfo.LastWriteTime };
group by into
var query =
from inventor in inventors
group inventor by inventor.Country into groups
from item in groups
orderby item.Country, item.Name
select new { groups.Key, groups.Count(), item.Name };
select嵌套、join连接
- 详细内容可以看《LINQ IN ACTION》。