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 }
运行结果: