C#入门经典 Part 6
Contents
CH 23
LINQ查询1
2
3
4
5
6var results =
from n in names
where n.StartsWith("S")
orderby n descending // orderby n.Substring(n.Length - 1)
select n // select new(n, ...)
;
方法语法1
2var results = names.OrderBy(n => n).Where(n => n.StartsWith("S"));
var results = names.OrderByDescending(n => n.Substring(n.Length - 1)).Where(n => n.StartsWith("S")).select(n => new(n, ...)).Distinct();
聚合运算符1
2
3
4
5results.Count();
results.Max();
results.Min();
results.Average();
results.Sum(n => (long) n);
Any, All1
2bool res = customers.Any(c => c.Name == "Tom");
bool res = customers.All(c => c.Name == "Tom");
多级排序1
2
3orderby c.Name, c.Age
var res = customers.OrderBy(c => c.Name).ThenBy(c => c.Age)...;
组合查询1
2
3
4
5var res =
from c in customers
group c by c.Region into cg
select new {TotalSales = cg.Sum(c => c.Sales), Region = cg.Key}
;
Take()
: 取前n个结果
Skip()
: 跳过前n个结果
First()
, FirstOrDefault()
: 返回第一个匹配给定条件的元素
集合运算符Intersect()
, Except()
, Union()
Join查询1
2
3
4var res =
from c in customers
join o in orders on c.ID equals o.ID
;