LinQ Coding -- (3)[Let子句]
在查询表达式中,存储子表达式的结果有时很有用,这样可以在随后的子句中使用。可以使用 let 关键字完成这一工作,该关键字可以创建一个新的范围变量,并且用您提供的表达式的结果初始化该变量。一旦用值初始化了该范围变量,它就不能用于存储其他值。但如果该范围变量存储的是可查询的类型,则可以对其进行查询。
1 public class LetFromLinq : Interface
2 {
3 #region Interface Members
4
5 public void invoke()
6 {
7 String[] strs = { "A penny saved is a penny earned.",
8 "The early bird catches the worm.",
9 "The pen is mightier than the sword." };
10
11 //使查询只能对范围变量 word 调用一次 ToLower。如果不使用 let,则必须在 where 子句的每个谓词中调用 ToLower。
12 var earlyBirdQuery = from sentence in strs
13 let words = sentence.Split(' ') //用空格分隔strs数组
14 from word in words
15 let w = word.ToLower() //把数组元素进行小写操作
16 where w[0] == 'the'
17 select word;
18
19 foreach (var v in earlyBirdQuery)
20 {
21 Console.WriteLine("\"{0}\" starts with a vowel", v);
22 }
23
24 Console.WriteLine("Press any key to exit.");
25 Console.ReadKey();
26 }
27
28 #endregion
29 }
2 {
3 #region Interface Members
4
5 public void invoke()
6 {
7 String[] strs = { "A penny saved is a penny earned.",
8 "The early bird catches the worm.",
9 "The pen is mightier than the sword." };
10
11 //使查询只能对范围变量 word 调用一次 ToLower。如果不使用 let,则必须在 where 子句的每个谓词中调用 ToLower。
12 var earlyBirdQuery = from sentence in strs
13 let words = sentence.Split(' ') //用空格分隔strs数组
14 from word in words
15 let w = word.ToLower() //把数组元素进行小写操作
16 where w[0] == 'the'
17 select word;
18
19 foreach (var v in earlyBirdQuery)
20 {
21 Console.WriteLine("\"{0}\" starts with a vowel", v);
22 }
23
24 Console.WriteLine("Press any key to exit.");
25 Console.ReadKey();
26 }
27
28 #endregion
29 }