LINQ之let关键字

Posted 寻找薛定谔的猫

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LINQ之let关键字相关的知识,希望对你有一定的参考价值。

let子句用于在LINQ表达式中存储子表达式的计算结果。let子句创建一个范围变量来存储结果,变量被创建后,不能修改或把其他表达式的结果重新赋值给它。
此范围变量可以再后续的LINQ子句中使用。

实例1

 1 int[] numbers = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
 2 
 3 //传统下的子查询做法
 4 //var query = from num in numbers
 5 //            select num * (from n in numbers
 6 //                          where n % 2 == 0
 7 //                          select n).Count();
 8 
 9 //使用LET关键字的做法
10 var query = from num in numbers
11          let evenNumbers = from n in numbers
12                     where n % 2 == 0
13                          select n
14         select num * evenNumbers.Count();
15 
16 foreach (var item in query)
17 {
18     Console.WriteLine(item);
19 } 

运行结果:0 5 10 15 20 25 30 35 40 45

实例2

 1 string[] strings = { "A penny saved is a penny earned.", "The aaxly sdj", "the pa is no" };
 2 
 3 var query = from sentence in strings
 4             let words = sentence.Split(\' \')//用空格分割成数组                
 5             from word in words
 6             let w = word.ToLower()//把每个字母小写        
 7             where w[0] == \'a\' || w[0] == \'e\'
 8             select word;
 9 
10 foreach (var s in query)
11 {
12     Console.WriteLine(s);
13 }

 

运行结果:

实例3

 1 List<Person> persons = new List<Person>
 2 {
 3     new Person { ID = "0001", Name = "张三" ,Gender = "" , Age = 18},
 4     new Person { ID = "0002", Name = "李四" ,Gender = "" , Age = 17},
 5     new Person { ID = "0003", Name = "王五" ,Gender = "" , Age = 19},
 6     new Person { ID = "0004", Name = "赵六" ,Gender = "", Age = 20}
 7 };
 8 var query = from p in persons
 9             let friendlyName = p.Gender == "" ? "Mr" + p.Name : "Ms" + p.Name
10             select new
11             {
12                 UserID = p.ID,
13                 FriendName = friendlyName
14             };
15 foreach (var item in query)
16 {
17     Console.WriteLine("No:{0},Friendly Name:{1}", item.UserID, item.FriendName);
18 }

运行结果:

 实例4

 1 List<Person> persons = new List<Person>
 2 {
 3     new Person { ID = "0001", Name = "张三" ,Gender = "" , Age = 18},
 4     new Person { ID = "0002", Name = "李四" ,Gender = "" , Age = 17},
 5     new Person { ID = "0003", Name = "王五" ,Gender = "" , Age = 19},
 6     new Person { ID = "0004", Name = "赵六" ,Gender = "", Age = 20}
 7 };
 8 
 9 var query = from p in persons
10             let gender = p.Gender
11             let age = p.Age
12             where age > 18 && gender == ""
13             select p;
14 foreach (var item in query)
15 {
16     Console.WriteLine("姓名: " + item.Name + "  年龄:" + item.Age);
17 }

运行结果:

以上是关于LINQ之let关键字的主要内容,如果未能解决你的问题,请参考以下文章

等效于链式 LINQ 扩展方法调用中的 'let' 关键字的代码

等效于链式 LINQ 扩展方法调用中的 'let' 关键字的代码

读书笔记 C# Linq查询之group关键字浅析

Linq善解人意之通过MSDN对14个“查询关键字“逐个解剖

LINQ 学习路程 -- 查询操作 let into关键字

用下面的代码解释一下javascript中var和let关键字的区别