总目录
C# 语法总目录
上一篇:LINQ(二) —— 流式语句
LINQ 三 ——查询表达式/into关键字/let关键字
2.查询表达式
- 延迟执行特性:查询语句构造完成后, 并不会立即执行,而是等到foreach里面才执行,在这执行之前,如果新增了元素,那么元素在foreach里也或生效。
- 临时使用外部变量:当foreach前改变lambda表达式里面的外部变量值,那么构造的语句也会根据外部变量改变而改变
//延迟执行特性
List<int> list = new List<int> { 1 };
IEnumerable<int> intEnu = list.Select(n => n * 10);
list.Add(2);
foreach (var item in intEnu)
{
Console.WriteLine(item);
}
//10
//20
//临时修改外部变量
List<int> list = new List<int> { 1,2};
int mul = 10;
IEnumerable<int> intEnu = list.Select(n => n * mul);
foreach (var item in intEnu)
{
Console.WriteLine(item);
}
Console.WriteLine("-----------------");
//临时修改外部变量
mul = 100;
foreach (var item in intEnu)
{
Console.WriteLine(item);
}
//10
//20
//-----------------
//100
//200
3. 子查询
就是把一个LINQ作为另一个LINQ的输入
4. into 关键字
使用into关键字,将原始查询重命名,其他都是一样的,性能也不变。
另外,into关键字只能在Select和Group后面添加。
string[] names = { "Tom", "Jerry", "kate", "Lucy", "Micky" };
IEnumerable<string> strName =
from n in names
where names.Length > 3
select n.Replace('y', 'Y')
into na
where na.Length > 3
select na;
foreach (var item in strName)
{
Console.WriteLine(item);
}
//JerrY
//kate
//LucY
//MickY
5. let 关键字
let关键字作用是,能够在LINQ中使用一个临时变量来储存临时结果,然后对这个临时结果进行处理。
string[] names = { "Tom", "Jerry", "kate", "Lucy", "Micky", "li", "zh" };
var query =
from n in names
let temp = n.Replace('y', 'Y')
where temp.Length > 2
orderby temp descending
select temp;
foreach (var item in query)
{
Console.WriteLine(item);
}
//输出
Tom
MickY
LucY
kate
JerrY
总目录
C# 语法总目录
上一篇:LINQ(二) —— 流式语句