3月12日 Ling复合查询和yield关键字

1.Linq复合查询注意的问题,有三种策略(LinqPad中的Chapter8的Composition Strategies中的例子),3条英文理解可能不太正确哈!

1.渐进结构(Progressive query construction)
IEnumerable<string> query =
                            from   n in names
                            select n.Replace ("a", "").Replace ("e", "").Replace ("i", "")
                            .Replace ("o", "").Replace ("u", "");

query = from n in query where n.Length > 2 orderby n select n;

RESULT: { "Dck", "Hrry", "Mry" }

2.使用into关键字(Using the into keyword)

IEnumerable<string> query =
                           from   n in names
                           select n.Replace ("a", "").Replace ("e", "").Replace ("i", "")
                           .Replace ("o", "").Replace ("u", "")
                           into noVowel
                           where noVowel.Length > 2 orderby noVowel select noVowel;

3.封装查询(Wrapping Queries)

IEnumerable<string> query =
                           from n1 in
                          (
                               from   n2 in names
                               select n2.Replace ("a", "").Replace ("e", "").Replace ("i", "")
                               .Replace ("o", "").Replace ("u", "")
                          )
                           where n1.Length > 2 orderby n1 select n1;
用这种方法可以替代前两种,但要注意避免不必要的子查询

2.yield关键字的使用

 直接看代码


代码
 1        static IEnumerable<int> WithNoYield()
 2         {
 3             IList<int> list = new List<int>();
 4             for (int i = 0; i < 20; i++)
 5             {
 6                 Console.WriteLine(i.ToString());
 7                 if (i > 2)
 8                     list.Add(i);
 9             }
10             return list;
11         }
12 
13 
14 
15         static IEnumerable<int> WithYield()
16         {
17             for (int i = 0; i < 20; i++)
18             {
19                 if (i > 2)
20                     yield return i;
21             }
22         }
23 
24         static void Main(string[] args)
25         {
26             //WithNoYield();
27             //Console.ReadLine();
28 
29             foreach (var item in WithYield())
30             {
31 
32                 Console.WriteLine(item);
33             };
34             Console.ReadLine();
35 
36         }

 

 yield使用起来很方便,是吧~但是要注意,它也是延迟加载的,当foreach执行时,才取值,下次循环时从上次结束位置继续取值

posted @ 2010-03-12 15:27  Cleary  阅读(154)  评论(0)    收藏  举报